最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PHP依賴(lài)倒置(Dependency Injection)代碼實(shí)例

 更新時(shí)間:2014年10月11日 12:08:16   作者:十年燈  
這篇文章主要介紹了PHP依賴(lài)倒置(Dependency Injection)代碼實(shí)例本文只提供實(shí)現(xiàn)代碼,需要的朋友可以參考下

實(shí)現(xiàn)類(lèi):

復(fù)制代碼 代碼如下:

<?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;
    }
}

實(shí)現(xiàn)實(shí)例:

復(fù)制代碼 代碼如下:

<?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);

相關(guān)文章

最新評(píng)論

金坛市| 道孚县| 木里| 茂名市| 漳平市| 兰考县| 鄂尔多斯市| 五台县| 广德县| 错那县| 什邡市| 崇明县| 应城市| 含山县| 景德镇市| 大冶市| 泰安市| 东丰县| 靖江市| 中超| 琼海市| 乡宁县| 兴文县| 饶阳县| 肥城市| 全州县| 瑞丽市| 浦江县| 汤原县| 衢州市| 鹿邑县| 米林县| 洛川县| 罗平县| 涞水县| 霍州市| 迁安市| 盖州市| 嵊泗县| 丹阳市| 略阳县|