• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于PHP的依赖倒置(Dependency Injection)

php 搞代码 3年前 (2022-01-22) 19次浏览 已收录 0个评论

这篇文章主要介绍了PHP依赖倒置(Dependency Injection)代码实例本文只提供实现代码,需要的朋友可以参考下

实现类:

<?php class Container{    protected $setings = array();     public function set($abstract, $concrete = null)    {        if ($concrete === null) {            $concrete = $abstract;        }         $this->setings[$abstract] = $concrete;    }     public function ge<em style="color:transparent">本@文来源[email protected]搞@^&代*@码网(</em><q>搞代gaodaima码</q>t($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和jQuery 注册模块的开发

关于PHP – EasyUI DataGrid 资料存的方法介绍

以上就是关于PHP的依赖倒置(Dependency Injection)的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于PHP的依赖倒置(Dependency Injection)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址