2011-08-21 15:36:51 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace DesignPatterns;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Multiton pattern
|
|
|
|
*
|
2013-09-03 14:52:42 +02:00
|
|
|
* --------------------------------------------------------------------------------------------------------------
|
|
|
|
* THIS IS CONSIDERED TO BE AN ANTI-PATTERN! FOR BETTER TESTABILITY AND MAINTAINABILITY USE DEPENDENCY INJECTION!
|
|
|
|
* --------------------------------------------------------------------------------------------------------------
|
|
|
|
*
|
2011-08-21 15:36:51 +02:00
|
|
|
* Purpose:
|
|
|
|
* to have only a list of named instances that are used, like a singleton but with n instances
|
|
|
|
*
|
|
|
|
* Examples:
|
|
|
|
* - 2 DB Connectors, e.g. one for MySQL, the other for SQLite
|
|
|
|
* - multiple Loggers (one for debug messages, one for errors)
|
|
|
|
*
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
class Multiton
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* the first instance
|
|
|
|
*/
|
|
|
|
const INSTANCE_1 = '1';
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* the second instance
|
|
|
|
*/
|
|
|
|
const INSTANCE_2 = '2';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* holds the named instances
|
|
|
|
*
|
|
|
|
* @var array
|
|
|
|
*/
|
2013-09-21 22:17:54 +02:00
|
|
|
private static $instances = array();
|
2011-08-21 15:36:51 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* should not be called from outside: private!
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
private function __construct()
|
|
|
|
{
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* gets the instance with the given name, e.g. Multiton::INSTANCE_1
|
2011-08-23 11:52:46 +02:00
|
|
|
* uses lazy initialization
|
2011-08-21 15:36:51 +02:00
|
|
|
*
|
|
|
|
* @param string $instanceName
|
2013-09-21 22:17:54 +02:00
|
|
|
*
|
2011-08-21 15:36:51 +02:00
|
|
|
* @return Multiton
|
|
|
|
*/
|
|
|
|
public static function getInstance($instanceName)
|
|
|
|
{
|
2013-09-21 22:17:54 +02:00
|
|
|
if (!array_key_exists($instanceName, self::$instances)) {
|
|
|
|
self::$instances[$instanceName] = new self();
|
2011-08-21 15:36:51 +02:00
|
|
|
}
|
|
|
|
|
2013-09-21 22:17:54 +02:00
|
|
|
return self::$instances[$instanceName];
|
2011-08-21 15:36:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* prevent instance from being cloned
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
private function __clone()
|
|
|
|
{
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* prevent instance from being unserialized
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
private function __wakeup()
|
|
|
|
{
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|