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

Parsing PHP Dependency Injection and Inversion of Control

巴扎黑
巴扎黑Original
2017-08-08 13:55:442739browse

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语句就省略不写了
  }
 }

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");
  }
 }

The sample class becomes:


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

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();

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处理类
 ...

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;
  }
 }

Instantiate example When it becomes:


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

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();

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:
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