源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

PHP依赖倒置(Dependency Injection)代码实例

  • 时间:2022-12-30 08:44 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP依赖倒置(Dependency Injection)代码实例
[b]实现类:[/b]
[u]复制代码[/u] 代码如下:
<?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;     } }
[b]实现实例:[/b]
[u]复制代码[/u] 代码如下:
<?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);
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部