


Dependency injection and inversion of control in php, php injection inversion_PHP tutorial
php dependency injection and inversion of control, php injection inversion
DI——Dependency Injection Dependency Injection
IoC——Inversion of Control
To understand the above two concepts, you must understand the following questions:
1. Who are the participants?
Answer: Generally there are three parties, one is an object; one is the IoC/DI container; and the other is an external resource of an object. Let me explain the nouns again. An object refers to any ordinary Java object; the IoC/DI container simply refers to a framework program used to implement IoC/DI functions; the external resources of the object refer to the object. Needed, but obtained from outside the object, are collectively referred to as resources, such as: other objects needed by the object, or file resources needed by the object, etc.
2. Dependence: Who depends on whom? Why are there dependencies?
Answer: An object depends on the IoC/DI container. Dependencies are inevitable. In a project, there are various relationships between various classes, and it is impossible for them all to be completely independent, which forms dependencies. Traditional development uses direct calls when using other classes, which will form strong coupling, which should be avoided. Dependency injection borrows containers to transfer dependent objects to achieve decoupling.
3. Injection: Who injects into whom? What exactly is injected?
Answer: Inject the external resources needed into the object through the container
4. Inversion of control: Who controls whom? Control what? Why is it called reversal?
Answer: The container control object of IoC/DI mainly controls the creation of object instances. Reversal is relative to positive direction, so what counts as positive direction? Think about the application under normal circumstances. If you want to use C inside A, what would you do? Of course, the object of C is created directly, that is, the required external resource C is actively obtained in class A. This situation is called forward. So what is reverse? That is, class A no longer actively obtains C, but passively waits for the IoC/DI container to obtain an instance of C, and then injects it into class A in reverse.
5. Are dependency injection and inversion of control the same concept?
Answer: As can be seen from the above: Dependency injection is described from the perspective of the application. Dependency injection can be described completely: the application relies on the container to create and inject the external resources it needs; and inversion of control is from the perspective of the application. The description is from the perspective of the container. The complete description is: the container controls the application, and the container reversely injects the external resources required by the application into the application.
Let’s take a look at some implementation methods of dependency injection through examples:
1.Constructor injection
<?<span>php </span><span>class</span><span> Book { </span><span>private</span> <span>$db_conn</span><span>; </span><span>public</span> <span>function</span> __construct(<span>$db_conn</span><span>) { </span><span>$this</span>->db_conn = <span>$db_conn</span><span>; } }</span>
2. Setter injection
<?<span>php<br /> <br />class book{<br /> private $db;<br /> private $file;<br /> function setdb($db){<br /> $this->db=$db;<br /> }<br /> function setfile($file){<br /> $this->file=$file;<br /> }<br />}<br />class file{}<br />class db{}<br />...<br /><br />class test{<br /></span><span> $book</span> = <span>new</span><span> Book(); </span><span>$book</span>->setdb(<span>new db()</span><span>); <br /></span><span> $book->setfile(new file());<br />} </span>?>
The code of the above two methods is very clear, but when we need to inject many dependencies, it means adding a lot of lines, which will be more difficult to manage.
A better solution is to create a class as the container for all dependencies. In this class, you can store, create, obtain, and find the required dependencies
<?<span>php </span><span>class</span><span> Ioc { </span><span>protected</span> <span>$db_conn</span><span>; </span><span>public</span> <span>static</span> <span>function</span><span> make_book() { </span><span>$new_book</span> = <span>new</span><span> Book(); </span><span>$new_book</span>->set_db(self::<span>$db_conn</span><span>); </span><span>//</span><span>... //... //其他的依赖注入</span> <span>return</span> <span>$new_book</span><span>; } }</span>
At this time, if you want to obtain a book instance, you only need to execute $newone = Ioc::makebook();
The above is a specific example of container. It is better not to write a specific dependency injection method. It is better to use registry registration and get acquisition.
<?<span>php </span><span>class</span><span> Ioc { </span><span>/*</span><span>* * @var 注册的依赖数组 </span><span>*/</span> <span>protected</span> <span>static</span> <span>$registry</span> = <span>array</span><span>(); </span><span>/*</span><span>* * 添加一个resolve到registry数组中 * @param string $name 依赖标识 * @param object $resolve 一个匿名函数用来创建实例 * @return void </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> register(<span>$name</span>, Closure <span>$resolve</span><span>) { </span><span>static</span>::<span>$registry</span>[<span>$name</span>] = <span>$resolve</span><span>; } </span><span>/*</span><span>* * 返回一个实例 * @param string $name 依赖的标识 * @return mixed </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> resolve(<span>$name</span><span>) { </span><span>if</span> ( <span>static</span>::registered(<span>$name</span><span>) ) { </span><span>$name</span> = <span>static</span>::<span>$registry</span>[<span>$name</span><span>]; </span><span>return</span> <span>$name</span><span>(); } </span><span>throw</span> <span>new</span> <span>Exception</span>('Nothing registered with that name, fool.'<span>); } </span><span>/*</span><span>* * 查询某个依赖实例是否存在 * @param string $name id * @return bool </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> registered(<span>$name</span><span>) { </span><span>return</span> <span>array_key_exists</span>(<span>$name</span>, <span>static</span>::<span>$registry</span><span>); } }</span>
You can now register and inject a
through the following methods<?<span>php </span><span>$book</span> = Ioc::registry('book', <span>function</span><span>(){ </span><span>$book</span> = <span>new</span><span> Book; </span><span>$book</span>->setdb('...'<span>); </span><span>$book</span>->setprice('...'<span>); </span><span>return</span> <span>$book</span><span>; }); </span><span>//</span><span>注入依赖</span> <span>$book</span> = Ioc::resolve('book'<span>); </span>?>
Reference: http://www.4wei.cn/archives/1002316

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

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

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

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

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.
