国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

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

2024-05-04 23:26:02
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了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);
 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 班戈县| 新晃| 治多县| 离岛区| 军事| 兴山县| 双鸭山市| 高州市| 中牟县| 陵川县| 西安市| 呼玛县| 洛宁县| 图们市| 平原县| 调兵山市| 宜兴市| 桦南县| 阳东县| 濮阳县| 临城县| 平凉市| 镇原县| 梨树县| 安阳县| 称多县| 客服| 汉川市| 汨罗市| 天祝| 景东| 河北区| 望谟县| 中西区| 洮南市| 新源县| 博白县| 桓仁| 十堰市| 灵武市| 天镇县|