How to write a lightweight container in php

小云云
Release: 2023-03-21 20:52:02
Original
1990 people have browsed it

Understand what Di/IoC is, dependency injection/inversion of control. The two are talking about the same thing, which is a popular design pattern at the moment. The general meaning is to prepare a box (container), throw the classes that may be used in the project into it in advance, and take them directly from the container in the project, which avoids directly adding new everywhere in the project, causing a lot of coupling. Instead, add setDi() and getDi() methods to the project class and manage the class through Di.

Let’s go directly to the code.

Di container class:

class Di implements \ArrayAccess{  
    private $_bindings = array();//服务列表  
    private $_instances = array();//已经实例化的服务  
      
    //获取服务  
    public function get($name,$params=array()){  
        //先从已经实例化的列表中查找  
        if(isset($this->_instances[$name])){  
            return $this->_instances[$name];  
        }  
          
        //检测有没有注册该服务  
        if(!isset($this->_bindings[$name])){  
            return null;  
        }  
          
        $concrete = $this->_bindings[$name]['class'];//对象具体注册内容  
          
        $obj = null;  
        //匿名函数方式  
        if($concrete instanceof \Closure){  
            $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;  
        }  
          
        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);  
    }  
}
Copy after login
<?php  
header("Content-Type:text/html;charset=utf8");  
class A{  
    public $name;  
    public $age;  
    public function __construct($name=""){  
        $this->name = $name;  
    }  
}  
  
include "Di.class.php";  
$di = new Di();  
//匿名函数方式注册一个名为a1的服务  
$di->setShared(&#39;a1&#39;,function($name=""){  
    return new A($name);  
});  
//直接以类名方式注册  
$di->set(&#39;a2&#39;,&#39;A&#39;);  
//直接传入实例化的对象  
$di->set(&#39;a3&#39;,new A("小唐"));  
  
$a1 = $di->get(&#39;a1&#39;,array("小李"));  
echo $a1->name."<br/>";//小李  
$a1_1 = $di->get(&#39;a1&#39;,array("小王"));  
echo $a1->name."<br/>";//小李  
echo $a1_1->name."<br/>";//小李  
  
$a2 = $di->get(&#39;a2&#39;,array("小张"));  
echo $a2->name."<br/>";//小张  
$a2_1 = $di->get(&#39;a2&#39;,array("小徐"));  
echo $a2->name."<br/>";//小张  
echo $a2_1->name."<br/>";//小徐  
  
$a3 = $di[&#39;a3&#39;];//可以直接通过数组方式获取服务对象  
echo $a3->name."<br/>";//小唐
Copy after login

Register services through set and setShared, support anonymous functions, class name strings , an object that has been instantiated.

The difference between the two is: registered in set mode, it will be re-instantiated every time it is obtainedsetShared method is only instantiated once, which is the so-called singleton mode
Of course, for direct registration of instantiated objects, such as the a3 service in the above code, the effect of set and setShared is the same.

Get the service through $di->get(), which accepts two parameters. The first parameter is the service name, such as a1, a2, a3 are required, and the second parameter is An array, the second parameter will be passed in as a parameter in an anonymous function or a parameter in a class constructor, refer to call_user_func_array().

Delete the service through

unset($di[&#39;a1&#39;]);
or
$di->remove(&#39;a1&#39;);
判断是否包含一个服务可以通过
isset($di[&#39;a1&#39;]);
or
$di->has(&#39;a1&#39;);
就这么多了。
Copy after login

Related recommendations:

html+css vertically centered container

WeChat How to implement the mini program scroll view container

PHP design pattern container deployment framework based on template engine

The above is the detailed content of How to write a lightweight container in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template