<?php class Di implements \ArrayAccess{ private $_bindings = array();//服務列表 private $_instances = array();//已經實例化的服務 //獲取服務 public function get($name,$params=array()){ //先從已經實例化的列表中查找 if(isset($this->_instances[$name])){ // no \Closure return $this->_instances[$name]; } //檢測有沒有註冊該服務 if(!isset($this->_bindings[$name])){ return null; } $concrete = $this->_bindings[$name]['class'];//對象具體註冊內容 $obj = null; //匿名函數方式 if($concrete instanceof \Closure){ echo "---"; print_r($name); echo "---"; $obj = call_user_func_array($concrete,$params); } //字符串方式 elseif(is_string($concrete)){ if(empty($params)){ $obj = new $concrete; }else{ //帶參數的類實例化,使用反射 $class = new \ReflectionClass($concrete); $obj = $class->newInstanceArgs($params); } } //如果是共享服務,則寫入_instances列表,下次直接取回 if($this->_bindings[$name]['shared'] == true && $obj){ $this->_instances[$name] = $obj; } print_r($obj); return $obj; } //檢測是否已經綁定 public function has($name){ return isset($this->_bindings[$name]) or isset($this->_instances[$name]); } //卸載服務 public function remove($name){ unset($this->_bindings[$name],$this->_instances[$name]); } //設置服務 public function set($name,$class){ $this->_registerService($name, $class); } //設置共享服務 public function setShared($name,$class){ $this->_registerService($name, $class, true); } //註冊服務 private function _registerService($name,$class,$shared=false){ $this->remove($name); if(!($class instanceof \Closure) && is_object($class)){ $this->_instances[$name] = $class; }else{ $this->_bindings[$name] = array("class"=>$class,"shared"=>$shared); } } //ArrayAccess接口,檢測服務是否存在 public function offsetExists($offset) { return $this->has($offset); } //ArrayAccess接口,以$di[$name]方式獲取服務 public function offsetGet($offset) { return $this->get($offset); } //ArrayAccess接口,以$di[$name]=$value方式註冊服務,非共享 public function offsetSet($offset, $value) { return $this->set($offset,$value); } //ArrayAccess接口,以unset($di[$name])方式卸載服務 public function offsetUnset($offset) { return $this->remove($offset); } } header("Content-Type:text/html;charset=utf8"); class A{ public $name; public $age; public function __construct($name=""){ $this->name = $name; } } $di = new Di(); //匿名函數方式註冊一個名爲a1的服務 $di->set('a1',function($name=""){ echo "--1-"; print_r($name); echo "--1-"; return new A($name); }); //直接以類名方式註冊 $di->set('a2','A'); //直接傳入實例化的對象 $di->set('a3',new A("小唐")); echo "<br/><pre> "; print_r($di); $a1 = $di->get('a1',array("小李")); echo $a1->name."<br/>";//小李 $a1_1 = $di->get('a1',array("小王")); echo $a1->name."w<br/>";//小李 echo $a1_1->name."<br/>";//小李 $a2 = $di->get('a2',array("小張")); echo $a2->name."<br/>";//小張 $a2_1 = $di->get('a2',array("小徐")); echo $a2->name."<br/>";//小張 echo $a2_1->name."<br/>";//小徐 $a3 = $di['a3'];//可以直接通過數組方式獲取服務對象 echo $a3->name."<br/>";//小唐
http://www.cjjjs.com/paper/gzsh/2017217135916798.aspx