Il pattern Singleton garantisce una sola istanza di una classe.
Implementazione
class Database {
private static ?Database $instance = null;
private PDO $connection;
private function __construct() {
$this->connection = new PDO(...);
}
// Previeni clonazione
private function __clone() {}
public static function getInstance(): Database {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection(): PDO {
return $this->connection;
}
}Utilizzo
$db = Database::getInstance();
$pdo = $db->getConnection();