1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
/**
* Singleton abstract class
*
* @author Delespierre
* @version 1.0.0
* @package cobalt\utilities
*/
abstract class Singleton extends Object implements Identifiable
{
/**
* Inner instance of singleton
* @var Singleton
*/
protected static $_instance;
/**
* Constructor visibility MUST be protected
*/
protected function __construct () {}
/**
* Protected method intended to initialize the object
*/
protected function _init() {}
/**
* Instance method
*
* Will create the instance if wasn't previously in use.
* Returns the inner and unique instance.
* May take as parameters the equivalent of the current
* child class constructor parameters.
*
* @throws Exception
* @return Singleton
*/
public static function instance ()
{
if (!isset(self::$_instance))
{
$c = static::whoami();
try { self::$_instance = new $c(); }
catch (Exception $e) { throw $e; }
// Initialize
if ($args = func_get_args())
{
switch (count($args))
{
case 0:
static::_init(); break;
case 1:
static::_init($args[0]); break;
case 2:
static::_init($args[0], $args[1]); break;
case 3:
static::_init($args[0], $args[1], $args[2]); break;
case 4:
static::_init($args[0], $args[1], $args[2], $args[3]); break;
case 5:
static::_init($args[0], $args[1], $args[2], $args[3], $args[4]); break;
default:
call_user_func_array(array(self::$_instance, "_init"), func_get_args()); break;
}
}
}
return self::$_instance;
}
/**
* Shorthand to access object methods from static context
*
* E.G.
* > SomeSingletonClass::someObjectMethod($a,$b,$c);
* Will be equivalent as
* > SomeSingletonClass::instance()->someObjectMethod($a,$b,$c)
*
* Will have the behavior of the called method or will
* throw a bad method call exception if the methods isn't callable.
*
* @param string $name
* @param array $args
* @throws BadMethodCallException
* @return mixed
*/
public static function __callStatic ($name, $args)
{
if (is_callable(array(self::instance(), $name)))
{
return call_user_func_array(array(self::instance(), $name), $args);
}
throw new BadMethodCallException("$name is innacessible for " . static::whoami());
}
} |
Partager