程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> PHP依賴倒置(Dependency Injection)代碼實例

PHP依賴倒置(Dependency Injection)代碼實例

編輯:PHP綜合

實現類:

復制代碼 代碼如下:
<?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);

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved