T要应用哪个是不明白的,是以,我们可以将其工厂化。【看上去很简单,在DI实际上有表现】
DI(重点来了)
起首,我们看一下PHP的psr规范。
http://www.php-fig.org/psr/psr-11/
官方定义的接口
Psr\Container\ContainerInterface
- class A{
- public function echo()
- {
- echo 'A'.PHP_EOL;
- }
- }
- class EchoT {
- protected $t;
- public function __construct()
- {
- $this->t = new A();
- }
- public function echo(){
- $this->t->echo();
- }
- }
包含两个办法
function has($id);
dependency injection container
细心看膳绫擎的工厂,是不是和get($id)很一致,PHP官方将其定义为容器(Container,我小我懂得,就是一个复杂的工厂)
依附注入容器
将T抽象出为接口,如许,EchoT类中的echo办法变成一个抽象的办法,不到运行那一刻,不知道他们的Method方法是怎么实现的。
- namespace Core;
- use Psr\Container\ContainerInterface;
- class Container implements ContainerInterface
- {
- protected $instance = [];//对象存储的数组
- public function __construct($path) {
- $this->_autoload($path); //起首我们要主动加载 psr-autoload
- }
- public function build($className)
- {
- if(is_string($className) and $this->has($className)) {
- return $this->get($className);
- }
- //反射
- $reflector = new \ReflectionClass($className);
推荐阅读
【51CTO晃荡】8.26 带你深度懂得清华大年夜学、搜狗基于算法的IT运维实践与摸索 本指南将向你介绍若何应用 Authconfig 在敕令行中将无图形界面的 CentOS 7 办事器集成到 Samba4 AD 域控制>>>详细阅读
本文标题:PHP如何实现依赖注入
地址:http://www.17bianji.com/lsqh/36755.html
1/2 1