PHP怎么依赖注入(Dependency Injection)的代码实例

分类:PHP_Python| 发布:llmaomi| 查看: | 发表时间:2014/12/15

实现类:

代码如下:
 <?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);
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/php-python/1817.html