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

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

实现类:

代码如下:
01<?php
02  
03class Container
04{
05    protected $setings = array();//@郑州网建
06  
07    public function set($abstract, $concrete = null)
08    {
09        if ($concrete === null) {
10            $concrete = $abstract;
11        }
12  
13        $this->setings[$abstract] = $concrete;
14    }
15  
16    public function get($abstract, $parameters = array())
17    {
18        if (!isset($this->setings[$abstract])) {
19            return null;
20        }
21  
22        return $this->build($this->setings[$abstract], $parameters);
23    }
24  
25    public function build($concrete, $parameters)
26    {
27        if ($concrete instanceof Closure) {
28            return $concrete($this, $parameters);
29        }
30  
31        $reflector = new ReflectionClass($concrete);//@郑州网建
32  
33        if (!$reflector->isInstantiable()) {
34            throw new Exception("Class {$concrete} is not instantiable");
35        }
36  
37        $constructor = $reflector->getConstructor();
38  
39        if (is_null($constructor)) {
40            return $reflector->newInstance();
41        }
42  
43        $parameters = $constructor->getParameters();
44        $dependencies = $this->getDependencies($parameters);
45  
46        return $reflector->newInstanceArgs($dependencies);
47    }
48  
49    public function getDependencies($parameters)
50    {
51        $dependencies = array();
52        foreach ($parameters as $parameter) {
53            $dependency = $parameter->getClass();
54            if ($dependency === null) {
55                if ($parameter->isDefaultValueAvailable()) {
56                    $dependencies[] = $parameter->getDefaultValue();
57                } else {
58                    throw new Exception("Can not be resolve class dependency {$parameter->name}");
59                }
60            } else {
61                $dependencies[] = $this->get($dependency->name);
62            }
63        }
64  
65        return $dependencies;
66    }
67}

实现实例:

代码如下:
01<?php
02  
03require 'container.php';
04  
05  
06interface MyInterface{}
07class Foo implements MyInterface{}
08class Bar implements MyInterface{}
09class Baz
10{
11    public function __construct(MyInterface $foo)
12    {
13        $this->foo = $foo;//@郑州网建
14    }
15}
16  
17$container = new Container();
18$container->set('Baz', 'Baz');
19$container->set('MyInterface', 'Foo');
20$baz = $container->get('Baz');
21print_r($baz);
22$container->set('MyInterface', 'Bar');
23$baz = $container->get('Baz');
24print_r($baz);
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/php-python/1817.html