An interesting article on singleton is an anti-pattern, although I do not quite agree. I never used a singleton as a standalone solution, I always associated it with a factory template, which, I think, discourages the state argument and encapsulation.
A good example of a singleton / factory solution is a database class. You can have several databases, each of which requires its own connection, but you do not want each call to create and create a new connection. You want to recycle common compounds to avoid land mines with “too many compounds”.
Something along the lines of:
/** * Database manager for handling database related stuff * Does use Zend_Db and Zend_Config */ class Database_Manager { protected static $dbos = array(); // Protected scope enforces encapsulation public static function getDbo($name) { // Init $hash = md5($name); // Attempt to use singleton if (array_key_exists($hash, self::$dbos)) { return self::$dbos[$hash]; } // Your db connection settings are set here either via // switch/case based on name, or loaded from a config file (yaml, xml, etc) $dbConnectionParams = array('your', 'connection', 'settings'); $config = new Zend_Config($dbConnectionParams); $dbo = Zend_Db::factory($config->database); // Adding to singleton so can be referenced in future calls self::$dbos[$hash] = $dbo; return $dbo; }
In this example, the factory provides encapsulation, while singleton processes already created database objects.
At the end of the day, it is up to you and what you want to support along the way.
source share