Singleton PHP database connection pattern

I was working on a small project using PHP and MySQL. I read a lot about best practices for connection management, etc.

I also implemented (after some posts found around) a singleton class for managing MySQL connections.

require_once 'config.inc.php'; class DbConn { private static $instance; private $dbConn; private function __construct() {} /** * * @return DbConn */ private static function getInstance(){ if (self::$instance == null){ $className = __CLASS__; self::$instance = new $className; } return self::$instance; } /** * * @return DbConn */ private static function initConnection(){ $db = self::getInstance(); $connConf = getConfigData(); $db->dbConn = new mysqli($connConf['db_host'], $connConf['db_user'], $connConf['db_pwd'],$connConf['db_name']); $db->dbConn->set_charset('utf8'); return $db; } /** * @return mysqli */ public static function getDbConn() { try { $db = self::initConnection(); return $db->dbConn; } catch (Exception $ex) { echo "I was unable to open a connection to the database. " . $ex->getMessage(); return null; } } } 

But ... If my site has approximately 10K visitors at a time, and I call every time my singleton object, should I expect that you have performance problems? I meant, shouldn't I have some kind of connection pool instead of a singleton?

+6
source share
1 answer

Using singletons in PHP is considered bad practice. In my experience, the unit test is the most problematic one. It is hard to make sure that the two tests are independent when testing single numbers.

I would delegate responsibility for the restriction "only one instance must exist" for the code as the Db object creates.

He is also looking for me since you do not understand Singletons in PHP. If you have 10,000 simultaneous requests, each request is executed in a separate process or thread, that is, everyone will have their own "singleton" instance.

They are not a "connection pool" in PHP, but you can use mysqli persistent connections. This can be achieved by passing p: in front of the host name when building mysqli. This may help here, but handle it with caution ( meaning to read the documentation first )


However, just for theory, a singleton in PHP should be aware that someone can use clone . The meaning in your case could be made like this:

 $db = DB::getInstance(); $db2 = clone $db; 

To avoid this, apply the __clone() method as follows:

 public function __clone() { throw new Exception("Can't clone a singleton"); } 

However, this was only for theory, I would recommend that you reorganize the class and throw away the Singleton pattern.

+8
source

All Articles