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); } }
<?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('a1',function($name=""){ return new A($name); }); //直接以类名方式注册 $di->set('a2','A'); //直接传入实例化的对象 $di->set('a3',new A("小唐")); $a1 = $di->get('a1',array("小李")); echo $a1->name."<br/>";//小李 $a1_1 = $di->get('a1',array("小王")); echo $a1->name."<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/>";//小唐
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['a1']); or $di->remove('a1'); 判断是否包含一个服务可以通过 isset($di['a1']); or $di->has('a1'); 就这么多了。
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!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
