Singleton pattern for communication with database

0

In PHP when I do a Singleton, an instance is created for every request that tries to open a connection to the database, or instantiating once it "always" will stay in memory for all requests ?

example:

class Connect{

    private static $conn;//qual o escopo dessa variavel?

    /**
    *   Padrão singleton
    */
    public static function getConnection(){
        if(self::$conn==NULL){
            //vai entrar aqui toda vez que uma requisição do usuario tenta uma comunicação com o bd?
            self::$conn= new PDO(...);
        }       
        return self::$conn;
    }
    
asked by anonymous 17.03.2016 / 12:26

1 answer

4

The Singleton pattern is just that (eventually it can be a bit more sophisticated). Being static there is no instantiation of fact. And the logic of the method ensures that the connection is opened only once, after all, the first time the private variable $conn , which has private scope (only the class sees it), is null, then a connection is established, after that , it no longer enters if and only returns the object of the connection. Then it will stay in memory while the script is running.

I usually say that this kind of thing is a lot of complication for something that will be very ephemeral, but it's fashionable to do so. Design patterns are often abused, Singleton is the champion of this, in PHP then ...

17.03.2016 / 13:08