实现类:
01 | <?php |
02 | |
03 | class 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 | |
03 | require 'container.php' ; |
04 | |
05 | |
06 | interface MyInterface{} |
07 | class Foo implements MyInterface{} |
08 | class Bar implements MyInterface{} |
09 | class 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' ); |
21 | print_r( $baz ); |
22 | $container ->set( 'MyInterface' , 'Bar' ); |
23 | $baz = $container ->get( 'Baz' ); |
24 | print_r( $baz ); |