首頁 >後端開發 >php教程 >關於PHP的依賴倒置(Dependency Injection)

關於PHP的依賴倒置(Dependency Injection)

不言
不言原創
2018-06-22 11:21:331785瀏覽

這篇文章主要介紹了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 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 &#39;container.php&#39;;
 
 
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(&#39;Baz&#39;, &#39;Baz&#39;);
$container->set(&#39;MyInterface&#39;, &#39;Foo&#39;);
$baz = $container->get(&#39;Baz&#39;);
print_r($baz);
$container->set(&#39;MyInterface&#39;, &#39;Bar&#39;);
$baz = $container->get(&#39;Baz&#39;);
print_r($baz);

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

關於PHP和jQuery 註冊模組的開發

##關於PHP – EasyUI DataGrid 資料存的方法介紹


#

以上是關於PHP的依賴倒置(Dependency Injection)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn