简单的IoC容器实现

 1 <?php
 2 
 3 class Container
 4 {
 5     protected $binds;
 6 
 7     protected $instances;
 8 
 9     public function bind($abstract, $concrete)
10     {
11         if ($concrete instanceof Closure) {
12             $this->binds[$abstract] = $concrete;
13         } else {
14             $this->instances[$abstract] = $concrete;
15         }
16     }
17 
18     public function make($abstract, $parameters = [])
19     {
20         
21         if (isset($this->instances[$abstract])) {
22             return $this->instances[$abstract];
23         }
24 
25         if(!is_array($parameters)){
26             $parameters=[$parameters];
27         }    
28         array_unshift($parameters, $this);
29 
30         return call_user_func_array($this->binds[$abstract], $parameters);
31     }
32 }
33 
34 class Power {
35     /**
36      * 能力值
37      */
38     protected $ability;
39 
40     /**
41      * 能力范围或距离
42      */
43     protected $range;
44 
45     public function __construct($ability, $range)
46     {
47         $this->ability = $ability;
48         $this->range = $range;
49     }
50 }
51 
52 
53 
54 
55 class Superman{
56 
57     private $power;
58 
59     public function __construct($power){
60 
61         $this->power=$power;
62 
63     }
64 
65 
66 }
67 
68 
69 $container=new Container();
70 
71 
72 $container->bind("superman",function($container,$mouleName){
73     return new Superman($container->make($mouleName));
74 });
75 
76 $container->bind("power",function($container){
77     return new Power(100,90);
78 });
79 
80 $superman=$container->make("superman","power");
81 
82 echo "<pre>";
83 var_dump($superman);
84 die;
85 
86 
87 
88 ?>

原文作者:chongyi
转自链接:https://learnku.com/articles/789/laravel-learning-notes-the-magic-of-the-service-container

 

posted @ 2021-12-15 17:42  念雷星  阅读(34)  评论(0编辑  收藏  举报