This pattern can be used to contain a registered Pools of Singletons, each distinguished by unique ID:
abstract class MultitonRegistryAbstract
{
/**
* @var array
*/
protected static $instances = [];
/**
* @param string $id
*/
final protected function __construct($id) {}
/**
* Get class name of lately binded class
*
* @return string
*/
final protected static function getClassName()
{
return get_called_class();
}
/**
* Instantiates a calling class object
*
* @return static
*/
public static function getInstance($id)
{
$className = static::getClassName();
if( !isset(self::$instances[$className]) ) {
self::$instances[$className] = [$id => new $className($id)];
} else {
if( !isset(self::$instances[$className][$id]) ) {
self::$instances[$className][$id] = new $className($id);
}
}
return self::$instances[$className][$id];
}
/**
* Deletes a calling class object
*
* @return void
*/
public static function unsetInstance($id)
{
$className = static::getClassName();
if( isset(self::$instances[$className]) ) {
if( isset(self::$instances[$className][$id]) ) {
unset(self::$instances[$className][$id]);
}
if( empty(self::$instances[$className]) ) {
unset(self::$instances[$className]);
}
}
}
/*-------------------------------------------------------------------------
| Seal methods that can instantiate the class
|------------------------------------------------------------------------*/
final protected function __clone() {}
final protected function __sleep() {}
final protected function __wakeup() {}
}
This is simplified form of pattern that can be used for ORM to store several entities of a given type.