I did a search on connections using singleton in the PDO, most people use a private or protected construct so that if there is no connection the same is created when instantiating a new Class (), but I wrote the code snippet using functions static and a static variable (which receives the connection) in the class presented below, and by my tests works quietly without recreating several connections, however I'm not sure if the code does the same effect as a singleton if someone can give feedback about the code thank you!
class Conexao {
private static $conexao = NULL;
const DB_HOST = "localhost";
const DB_NAME = "test";
const DB_USER = "root";
const DB_PASS = "12345678";
private static function conectar(){
if(empty(self::$conexao)){
try {
self::$conexao = new PDO('mysql:host='.self::DB_HOST.';dbname='.self::DB_NAME.';charset=utf8', self::DB_USER, self::DB_PASS);
self::$conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(!self::$conexao){
echo "Houve um erro ao efetuar a conexão!";
return null;
}
} catch(PDOException $e){
echo "Não foi possível efetuar a conexão ao banco de dados! ".$e->getMessage();
}
} else if(isset(self::$conexao)){
//Conexao já existe
}
var_dump(self::$conexao);
echo "<br>";
return self::$conexao instanceof PDO ? self::$conexao : null;
}
public static function QFA($q, $i){
return self::conectar()->query($q)->fetchAll(!$i ? PDO::FETCH_ASSOC : NULL);
}
}
try {
$x = Conexao::QFA("SELECT * FROM nomes");
//print_r($x);
$y = Conexao::QFA("SELECT * FROM nomes");
//print_r($y);
} catch(PDOException $e){
print_r($e->getMessage());
}