Is there a use-case for singletons with database access in PHP?

后端 未结 11 1826
名媛妹妹
名媛妹妹 2020-11-21 06:44

I access my MySQL database via PDO. I\'m setting up access to the database, and my first attempt was to use the following:

The first thing I thought of is glob

11条回答
  •  长情又很酷
    2020-11-21 07:33

    First, I just want to say that I don't find much uses to the Singleton pattern. Why would one want to keep a single object thorough the whole application? Especially for databases, what if I want to connect to another database server? I have to disconnect and reconnect every time...? Anyway...

    There are several drawbacks to using globals in an application (which is what the traditional use of the Singleton pattern does):

    • Difficult to unit test
    • Dependency injection issues
    • Can create locking issues (multi-threaded application)

    Use static classes instead of a singleton instance provides some of the same drawbacks as well, because the biggest problem of singleton is the static getInstance method.

    You can limit the number of instances a class can have without using the traditional getInstance method:

    class Single {
    
        static private $_instance = false;
    
        public function __construct() {
            if (self::$_instance)
               throw new RuntimeException('An instance of '.__CLASS__.' already exists');
    
            self::$_instance = true;
        }
    
        private function __clone() {
            throw new RuntimeException('Cannot clone a singleton class');
        }
    
        public function __destruct() {
            self::$_instance = false;
        }
    
    }
    
    $a = new Single;
    $b = new Single; // error
    $b = clone($a); // error
    unset($a);
    $b = new Single; // works
    

    This will help on the first the points mentioned above: unit testing and dependency injection; while still making sure a single instance of the class exist in your application. You could, per example, just pass the resulting object to your models (MVC pattern) for them to use.

提交回复
热议问题