Extend abstract singleton class
abstract-class, php, singleton
Solution
In PHP methods, `self` always refers to the class where the method is defined. Since version 5.3.0, PHP supports “late static binding”, where you can use the `static` keyword to access overridden static methods, as well as the function `get_called_class()` to get the name of the derived class in static context.
However, your design has a major flaw: The static property `$factory` defined in `Base_Factory` is shared across all derived classes. Therefore, the first time a singleton is created and stored in this property, all other calls to `getInstance()` will return the same object, no matter what derived class is used.
You could use a static dictionary mapping class names to singleton objects:
abstract class Base_Factory {
private static $_instances = array();
public static function getInstance() {
$class = get_called_class();
if (!isset(self::$_instances[$class])) {
self::$_instances[$class] = new $class();
}
return self::$_instances[$class];
}
}
Oh, one more thing: The fact that you are looking for a possibility to re-use code for singleton objects could be a cue to the fact that you are over-using the singleton design pattern! Ask yourself if the classes you are planning to implement as singletons really are singletons and if there will be no use case where you might want to have multiple instances of the particular class.
Often it is much better to use just one singleton representing the current “application context” that provides accessors for objects that are singletons with respect to this context.
Problem
If you had a factory class that creates new objects of some kind, and that factroy class is a singleton, like this: ``` class Database_Factory extends Base_Factory { private static $factory; private $objects = array(); public function __get($profile) { // check for object and return it if it's created before } public static function getInstance(){ if (!self::$factory) self::$factory = new self(); return self::$factory; } } ``` The same code repeats anytime where some object needs it's own factory. So i decided to make this factory class abstract and implement only specific routines for each factory. But PHP does not allow to instantiate abstract class. ``` abstract class Base_Factory { public static function getInstance(){ if (!self::$factory) self::$factory = new self(); return self::$factory; } } ``` Fatal error: Cannot instantiate abstract class Base_Factory What would you do?