php设计模式-简单依赖注入容器的闭包方式实现
Posted itxds
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php设计模式-简单依赖注入容器的闭包方式实现相关的知识,希望对你有一定的参考价值。
<?php class A { private $_b; public function __construct($b) { $this->_b = $b; } public function sayHello() { $this->_b->sayHello(); echo ‘I am A<br>‘; } } class B { private $_c; public function __construct($c) { $this->_c = $c; } public function sayHello() { $this->_c->sayHello(); echo ‘I am B<br>‘; } } class C { public function sayHello() { echo ‘I am C<br>‘; } } // 依赖注入容器 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设计模式-简单依赖注入容器的闭包方式实现的主要内容,如果未能解决你的问题,请参考以下文章