Singleton in conjunction with Factory pattern in PHP5

What is the best method to use a singleton design pattern in conjunction with a factory method pattern in PHP5? My easiest use case for this is to connect to a sample database only once for each type of database.

+4
source share
1 answer

singleton factory to connect to DB:

class Registry { private static $_objects; public static function set($key, $object) { if (!array_key_exists($key, self::$_objects)) self::$_objects[$key] = $object; } public static function get($key) { if (array_key_exists($key, self::$_objects)) return self::$_objects[$key]; else return false; } } class DBFactory { public static function getConnection($type) { switch ($type) { case 'pdo': if (!(Registry::get('DB_PDO') instaceof DbPdo)) Registry::set('DB_PDO', new DbPdo('user', 'pass', ...)); return Registry::get('DB_PDO') case 'mssql': //same for other connections //... } } } 

using:

 $factory = DBFactory::getConnection('pdo'); 

Singletones are no longer needed because all methods can be called statically ... But database classes can still be considered single, because there will be only one instance in your application.

Thus, the same effect is created using the factory and registry templates.

The registry can be replaced by making your database classes singleton, then the factory will look like this:

 class DBFactory { public static function getConnection($type) { switch ($type) { case 'pdo': return DbPdo::getInstance('user', 'pass', ...); case 'mssql': //same for other connections //... } } } class DbPdo { private static $_instance; private function __construct($user, $pass, ...){ //instantiate object } public static function getInstance($user = null, $pass = null, ...) { if (!(self::$_instance instanceof DbPdo)) self::$_instance = new DbPdo($user, $pass, ...); return self::$_instance; } } 

Thus, you have the choice to make all your single single database objects or use the registry. I personally would have done with the registry, because it can be used to store any types of objects, even those where you do not want the class to be singleton.

The choice of design is always personalized imo ...

+10
source