Home Backend Development PHP Tutorial Parsing PHP Dependency Injection and Inversion of Control

Parsing PHP Dependency Injection and Inversion of Control

Aug 08, 2017 pm 01:55 PM
php reverse control

This article mainly introduces the relevant information of PHP Dependency Injection (DI) and Inversion of Control (IoC), which has certain reference value. Interested friends can refer to it

First Dependency Injection It talks about the same thing as inversion of control. It is a design pattern. This design pattern is used to reduce the coupling between programs. I studied it for a while and saw that there is no related article on the TP official website, so I wrote this introduction. Let’s take a look at this design pattern, hoping to contribute some strength to the TP community.

First of all, don’t pursue the definition of this design pattern, otherwise you will definitely be confused. The author is deeply affected by it. There are many articles on Baidu, all of which are described from a theoretical perspective. There are a lot of unfamiliar vocabulary, or it is described by java code, which is also unfamiliar.

No matter what, I finally have some clarity. Let’s describe the concept of dependency injection from the perspective of PHP.

Let’s first assume that we have a class here, which needs to use a database connection. According to the most primitive method, we may write this class like this:


class example {
  
  private $_db;
  function __construct(){
    include "./Lib/Db.php";
    $this->_db = new Db("localhost","root","123456","test");
  }
  function getList(){
    $this->_db->query("......");//这里具体sql语句就省略不写了
  }
 }
Copy after login

Process:

Include the database class file in the constructor first;
Then pass in new Db and pass in the database connection information Instantiate the db class;
After that, the getList method can call the database class through $this->_db to implement database operations.

It seems that we have achieved the desired function, but this is the beginning of a nightmare. In the future, example1, example2, example3... more and more classes will need to use the db component. If they are all written like this If so, if one day the database password is changed or the db class changes, wouldn't it be necessary to go back and modify all class files?
ok, in order to solve this problem, the factory mode appeared. We created a Factory method and obtained the instance of the db component through the Factory::getDb() method:


class Factory {
  public static function getDb(){
    include "./Lib/Db.php";
    return new Db("localhost","root","123456","test");
  }
 }
Copy after login

The sample class becomes:


class example {
  
  private $_db;
  function __construct(){
    $this->_db = Factory::getDb();
  }
  function getList(){
    $this->_db->query("......");//这里具体sql语句就省略不写了
  }
 }
Copy after login

Is this perfect? Think again about all classes in the future, example1, example2, example3..., you need to obtain a Db instance through Factory::getDb(); in the constructor. In fact, you directly interact with the Db class from the original The coupling becomes coupling with the Factory class. The factory class just helps you package the database connection information. Although when the database information changes, you only need to modify the Factory::getDb() method, but suddenly one day the factory method The name needs to be changed, or the getDb method needs to be renamed, what should you do? Of course, this kind of demand is actually very messed up, but sometimes this situation does exist. One solution is:

We don’t instantiate the Db component from within the example class. We rely on injection from the outside. What? What does it mean? Look at the following example:


class example {
  private $_db;
  function getList(){
    $this->_db->query("......");//这里具体sql语句就省略不写了
  }
  //从外部注入db连接
  function setDb($connection){
    $this->_db = $connection;
  }
 }
 //调用
$example = new example();
$example->setDb(Factory::getDb());//注入db连接
$example->getList();
Copy after login

In this way, the example class is completely decoupled from the external class. You can see that there are no factory methods or methods in the Db class. Db class figure. We inject the connection instance directly into it by calling the setDb method of the example class from the outside. In this way, the example does not need to worry about how the db connection is generated.
This is called dependency injection. The implementation does not create a dependency relationship within the code, but passes it as a parameter. This makes our program easier to maintain, reduces the coupling of the program code, and achieves a loose coupling.

This is not over yet. Let us assume that in addition to db, other external classes are used in the example class. We pass:


$example->setDb(Factory::getDb());//注入db连接
$example->setFile(Factory::getFile());//注入文件处理类
$example->setImage(Factory::getImage());//注入Image处理类
 ...
Copy after login

We are not done yet. No need to write so many sets? Are you tired?
ok, in order to not have to write so many lines of code every time, we have another factory method:


class Factory {
  public static function getExample(){
    $example = new example();
    $example->setDb(Factory::getDb());//注入db连接
    $example->setFile(Factory::getFile());//注入文件处理类
    $example->setImage(Factory::getImage());//注入Image处理类
    return $expample;
  }
 }
Copy after login

Instantiate example When it becomes:


$example=Factory::getExample();
$example->getList();
Copy after login

It seems perfect, but why does it feel like it’s back to the scene when the factory method was used for the first time? This is indeed not a good solution, so another concept is proposed: containers, also called IoC containers and DI containers.

We originally injected various classes through the setXXX method. The code is very long and there are many methods. Although it can be packaged through a factory method, it is not so cool. Well, we don’t use the setXXX method, so that’s it. Without secondary packaging with factory methods, how can we implement dependency injection?
Here we introduce a convention: pass in a parameter named Di $di in the constructor of the example class, as follows:


class example {
  private $_di;
  function __construct(Di &$di){
    $this->_di = $di;
  }
  //通过di容器获取db实例
  function getList(){
    $this->_di->get('db')->query("......");//这里具体sql语句就省略不写了
  }
 }
$di = new Di();
$di->set("db",function(){
  return new Db("localhost","root","root","test"); 
 });
$example = new example($di);
$example->getList();
Copy after login

Di is IoC container, the so-called container is to store instances of various classes that we may use. We set an instance named db through $di->set(). Because it is passed in through a callback function, set The db class will not be instantiated immediately, but will be instantiated when $di->get('db'). Similarly, the singleton mode can also be integrated into the design of the di class.

In this way, we only need to declare a Di class in the global scope, put all the classes that need to be injected into the container, and then pass the container into example as a parameter of the constructor, and then in the example class Get the instance from the container. Of course, it doesn’t have to be a constructor. You can also use a setDi(Di $di) method to pass in the Di container. In short, the agreement is made by you, so you just need to know it yourself.

In this way, dependency injection and key container concepts have been introduced, and the rest is to use and understand it in practice!

The above is the detailed content of Parsing PHP Dependency Injection and Inversion of Control. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles