PHP PDO connection with static variable in class

Asked

Viewed 607 times

2

I did a research on connections using Singleton in PDO, in 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 static functions and a static variable (that receives the connection) in the class presented below, and by my tests works smoothly without recreating multiple connections, however I’m not entirely sure if the code does the same effect as a Singleton, if someone can give a feedback on 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());
}
  • But these functions and this variable are within a class ...

  • I edited the question. = D

  • It doesn’t have the same effect as a Singleton because one of Singleton’s premises is the private contractor. Nothing stops you from creating new PDO instances in your code. You can only use the Singleton standard in classes you create yourself. That’s why you can’t turn.

  • Correct, I agree with your explanation regarding the concept of Singleton (which is used by the private / protected constructor that characterizes it), but in case of use, instead of using Singleton in the class, make the connection as mentioned (in the code and explanation)would imply some problem in your opinion?

  • In this case how was shown where should I terminate (kill) the PDO connection? Inside the method I used the connection or inside the connect method()?

  • You can create a new static method in the class and within this method assign the static variable self::$connected = null and when it is executed the connection will receive null and will no longer be available. Have a look at this link http://php.net/manual/pdo.connections.php in the "Example #3 Closing a Connection".

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.