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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。