PHP依赖倒置(Dependency Injection)代码实例


Posted in PHP onOctober 11, 2014

实现类:

<?php

 

class Container

{

    protected $setings = array();

 

    public function set($abstract, $concrete = null)

    {

        if ($concrete === null) {

            $concrete = $abstract;

        }

 

        $this->setings[$abstract] = $concrete;

    }

 

    public function get($abstract, $parameters = array())

    {

        if (!isset($this->setings[$abstract])) {

            return null;

        }

 

        return $this->build($this->setings[$abstract], $parameters);

    }

 

    public function build($concrete, $parameters)

    {

        if ($concrete instanceof Closure) {

            return $concrete($this, $parameters);

        }

 

        $reflector = new ReflectionClass($concrete);

 

        if (!$reflector->isInstantiable()) {

            throw new Exception("Class {$concrete} is not instantiable");

        }

 

        $constructor = $reflector->getConstructor();

 

        if (is_null($constructor)) {

            return $reflector->newInstance();

        }

 

        $parameters = $constructor->getParameters();

        $dependencies = $this->getDependencies($parameters);

 

        return $reflector->newInstanceArgs($dependencies);

    }

 

    public function getDependencies($parameters)

    {

        $dependencies = array();

        foreach ($parameters as $parameter) {

            $dependency = $parameter->getClass();

            if ($dependency === null) {

                if ($parameter->isDefaultValueAvailable()) {

                    $dependencies[] = $parameter->getDefaultValue();

                } else {

                    throw new Exception("Can not be resolve class dependency {$parameter->name}");

                }

            } else {

                $dependencies[] = $this->get($dependency->name);

            }

        }

 

        return $dependencies;

    }

}

实现实例:

<?php

 

require 'container.php';

 

 

interface MyInterface{}

class Foo implements MyInterface{}

class Bar implements MyInterface{}

class Baz

{

    public function __construct(MyInterface $foo)

    {

        $this->foo = $foo;

    }

}

 

$container = new Container();

$container->set('Baz', 'Baz');

$container->set('MyInterface', 'Foo');

$baz = $container->get('Baz');

print_r($baz);

$container->set('MyInterface', 'Bar');

$baz = $container->get('Baz');

print_r($baz);
PHP 相关文章推荐
我的论坛源代码(七)
Oct 09 PHP
PHP 文件扩展名 获取函数
Jun 03 PHP
PHP5.3.1 不再支持ISAPI
Jan 08 PHP
str_replace只替换一次字符串的方法
Apr 09 PHP
php将gd生成的图片缓存到memcache的小例子
Jun 05 PHP
PHP-Java-Bridge使用笔记
Sep 22 PHP
ci检测是ajax还是页面post提交数据的方法
Nov 10 PHP
thinkphp3.2.2实现生成多张缩略图的方法
Dec 19 PHP
php使用parse_url和parse_str解析URL
Feb 22 PHP
PHP如何将log信息写入服务器中的log文件
Jul 29 PHP
php求数组全排列,元素所有组合的方法总结
Mar 14 PHP
PHP实现支持CURL字符串证书传输的方法
Mar 23 PHP
php实现设计模式中的单例模式详解
Oct 11 #PHP
PHP实现设计模式中的抽象工厂模式详解
Oct 11 #PHP
php中字符集转换iconv函数使用总结
Oct 11 #PHP
PHP生成网站桌面快捷方式代码分享
Oct 11 #PHP
PHP中执行cmd命令的方法
Oct 11 #PHP
PHP @ at 记号的作用示例介绍
Oct 10 #PHP
php json_encode()函数返回json数据实例代码
Oct 10 #PHP
You might like
Snoopy类使用小例子
2008/04/15 PHP
PHP 进程锁定问题分析研究
2009/11/24 PHP
使用php检测用户当前使用的浏览器是否为IE浏览器
2013/12/03 PHP
PHP异常Parse error: syntax error, unexpected T_VAR错误解决方法
2014/05/06 PHP
php冒泡排序与快速排序实例详解
2015/12/07 PHP
PHP双向链表定义与用法示例
2018/01/31 PHP
Javascript中的for in循环和hasOwnProperty结合使用
2013/06/05 Javascript
jQuery获得包含margin的outerWidth和outerHeight的方法
2015/03/25 Javascript
js实现不重复导入的方法
2016/03/02 Javascript
js处理层级数据结构的方法小结
2017/01/17 Javascript
Node.JS更改Windows注册表Regedit的方法小结
2017/08/18 Javascript
详解vue几种主动刷新的方法总结
2019/02/19 Javascript
微信小程序表单验证WxValidate的使用
2019/11/27 Javascript
Python实现的下载8000首儿歌的代码分享
2014/11/21 Python
在python 中实现运行多条shell命令
2019/01/07 Python
python 切换root 执行命令的方法
2019/01/19 Python
Python 3.8新特征之asyncio REPL
2019/05/28 Python
python装饰器常见使用方法分析
2019/06/26 Python
对python中url参数编码与解码的实例详解
2019/07/25 Python
tensorflow dataset.shuffle、dataset.batch、dataset.repeat顺序区别详解
2020/06/03 Python
python和JavaScript哪个容易上手
2020/06/23 Python
解决Python 写文件报错TypeError的问题
2020/10/23 Python
HTML+CSS3 模仿Windows7 桌面效果
2010/06/17 HTML / CSS
突袭HTML5之Javascript API扩展5—其他扩展(应用缓存/服务端消息/桌面通知)
2013/01/31 HTML / CSS
沃达丰英国有限公司:Vodafone英国
2019/04/16 全球购物
一些Unix笔试题和面试题
2012/09/25 面试题
职高毕业生自我鉴定
2013/10/21 职场文书
中学生校园广播稿
2014/01/16 职场文书
CAD制图人员的自荐信
2014/02/07 职场文书
捐资助学倡议书
2014/04/15 职场文书
2014报到证办理个人委托书
2014/10/08 职场文书
预备党员群众路线教育实践活动思想汇报2014
2014/10/25 职场文书
雨花台导游词
2015/02/06 职场文书
Golang之sync.Pool使用详解
2021/05/06 Golang
超级详细实用的pycharm常用快捷键
2021/05/12 Python
python装饰器代码解析
2022/03/23 Python