5
2016-09-18 16:34:19 +08:00 1
第一次回复,这种懒加载可以用闭包哦
class DB
{
private $binds = [];
private $instances = [];
public function __construct()
{
$this->bind('a', function ($config) {
return new A($config);
});
$this->bind('b', function ($config) {
return new B($config);
});
}
private function bind($key, Closure $closure)
{
if (!isset($this->binds[$key])) {
$this->binds[$key] = $closure;
}
}
public function make($key, array $params)
{
if (isset($this->instances[$key])) {
return $this->instances[$key];
}
if (!isset($this->binds[$key])) {
return false;
}
$this->instances[$key] = call_user_func_array($this->binds[$key], $params);
return $this->instances[$key];
}
}
class A
{
private $config;
public function __construct($config)
{
$this->config = $config;
}
public function foo()
{
echo "Class A:\n";
var_dump($this->config);
}
}
class B
{
private $config;
public function __construct($config)
{
$this->config = $config;
}
public function foo()
{
echo "Class B:\n";
var_dump($this->config);
}
}
$db = new DB();
$a = $db->make('a', ['config for a']);
$a->foo();
$b = $db->make('b', ['config for b']);
$b->foo();
这确实是单例+依赖注入的问题
DB 类一般是要做单例的,这里只是写个例子就直接 new 了,不对的话请指教