Created
March 14, 2013 16:57
-
-
Save bdelespierre/5163036 to your computer and use it in GitHub Desktop.
Singleton (boo) + Adapter (yay)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Singleton { | |
public static $aliases = array(); | |
protected static $_adapters = array(); | |
public function __construct () { | |
throw new LogicException("you cannot instanciate Singleton"); | |
} | |
public static function register ($adapter, array $config = array()) { | |
$class = $adapter; | |
if (isset(static::$aliases[$adapter])) | |
$class = (string)static::$aliases[$adapter]; | |
if (!class_exists($class, true)) | |
throw new RuntimeException("no such class $class"); | |
if (!in_array('SingletonAdapter', class_implements($class))) | |
throw new LogicException("$class doesn't implements SingletonAdapter"); | |
static::$_adapters[$adapter] = compact('class', 'config'); | |
} | |
public static function resolve ($adapter) { | |
if (!isset(static::$_adapters[$adapter])) | |
return false; | |
if (static::$_adapters[$adapter] instanceOf SingletonAdapter) | |
return static::$_adapters[$adapter]; | |
extract(static::$_adapters[$adapter]); | |
return static::$_adapters[$adapter] = new $class($config); | |
} | |
public static function __callStatic ($method, $args = array()) { | |
if (!$adapter = static::resolve($method)) | |
throw new RuntimeException("no such adapter $method"); | |
return $adapter->invoke($args); | |
} | |
} | |
interface SingletonAdapter { | |
public function __construct (array $config); | |
public function invoke (array $args); | |
} | |
class CallbackSingletonAdapter implements SingletonAdapter { | |
protected $_closure; | |
public function __construct (array $config) { | |
if (!isset($config['closure'])) | |
throw new RuntimeException("no closure provided"); | |
if (!$config['closure'] instanceOf Closure) | |
throw new RuntimeException("not a valid closure"); | |
$this->_closure = $config['closure']; | |
} | |
public function invoke (array $args) { | |
return call_user_func_array($this->_closure, $args); | |
} | |
} | |
$closure = function ($a, $b, $c) { | |
var_dump($a, $b, $c); | |
}; | |
Singleton::$aliases['a'] = 'CallbackSingletonAdapter'; | |
Singleton::register('a', compact('closure')); | |
Singleton::a(1,2,3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment