php设计模式-简单依赖注入容器的闭包方式实现
2021-01-17 20:16
标签:fun 结果 turn func callable isset contain public bin 结果: php设计模式-简单依赖注入容器的闭包方式实现 标签:fun 结果 turn func callable isset contain public bin 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13358081.html_b = $b;
}
public function sayHello()
{
$this->_b->sayHello();
echo ‘I am A
‘;
}
}
class B
{
private $_c;
public function __construct($c)
{
$this->_c = $c;
}
public function sayHello()
{
$this->_c->sayHello();
echo ‘I am B
‘;
}
}
class C
{
public function sayHello()
{
echo ‘I am C
‘;
}
}
// 依赖注入容器
class DIContainer
{
private $_container;
public function bind($key, Callable $resolver)
{
$this->_container[$key] = $resolver;
}
public function make($classname)
{
if (!isset($this->_container[$classname])) throw new Exception(‘unregister class:‘ . $classname);
return $this->_container[$classname]($this);
}
}
$container = new DIContainer();
$container->bind(‘c‘, function(){
return new C;
});
$container->bind(‘b‘, function($container){
return new B($container->make(‘c‘));
});
$container->bind(‘a‘, function($container){
return new A($container->make(‘b‘));
});
$a = $container->make(‘a‘);
$a->sayHello();
I am C
I am B
I am A
文章标题:php设计模式-简单依赖注入容器的闭包方式实现
文章链接:http://soscw.com/index.php/essay/43352.html