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':
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 ...