How to write a lightweight container in php
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
