Home > Backend Development > PHP Tutorial > Understanding php dependency injection and inversion of control, php dependency injection inversion_PHP tutorial

Understanding php dependency injection and inversion of control, php dependency injection inversion_PHP tutorial

WBOY
Release: 2016-07-12 08:52:48
Original
881 people have browsed it

Understand php dependency injection and inversion of control, php dependency injection inversion

To understand the two concepts of php dependency injection and inversion of control, you must understand the following issues :

DI——Dependency Injection

IoC——Inversion of Control

1. Who are the participants? ​

Answer: Generally there are three parties, one is an object; one is the container of IoC/DI; the other is the 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 it needs 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 more fully: the application depends on the container to create and inject it Required external resources; while inversion of control is described from the perspective of the container, the description is complete: the container controls the application, and the container reversely injects the external resources required by the application into the application.

Let’s take a closer look at some implementation methods of dependency injection through examples:

1. Constructor injection

<&#63;php
class Book {
  private $db_conn;
 
  public function __construct($db_conn) {
    $this->db_conn = $db_conn;
  }
}
Copy after login

2. Setter injection

<&#63;php

 
class book{
   private $db;
   private $file;
   function setdb($db){
     $this->db=$db;
   }
   function setfile($file){
     $this->file=$file;
   }
}
class file{}
class db{}
...

class test{
   $book = new Book();
    $book->setdb(new db()); 
   $book->setfile(new file());
}
&#63;>

Copy after login

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

<&#63;php
class Ioc {
  protected $db_conn;
  public static function make_book() {
    $new_book = new Book();
    $new_book->set_db(self::$db_conn);
    //...
    //...
    //其他的依赖注入
    return $new_book;
  }
}
Copy after login

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.

<&#63;php
class Ioc {
/**
* @var 注册的依赖数组
*/
 
  protected static $registry = array();
 
  /**
  * 添加一个resolve到registry数组中
  * @param string $name 依赖标识
  * @param object $resolve 一个匿名函数用来创建实例
  * @return void
  */
  public static function register($name, Closure $resolve)
  {
   static::$registry[$name] = $resolve;
  }
 
  /**
   * 返回一个实例
   * @param string $name 依赖的标识
   * @return mixed
   */
  public static function resolve($name)
  {
    if ( static::registered($name) )
    {
     $name = static::$registry[$name];
     return $name();
    }
    throw new Exception('Nothing registered with that name, fool.');
  }
  /**
  * 查询某个依赖实例是否存在
  * @param string $name id
  * @return bool 
  */
  public static function registered($name)
  {
   return array_key_exists($name, static::$registry);
  }
}
Copy after login

You can now register and inject one through the following methods

<&#63;php
$book = Ioc::registry('book', function(){
$book = new Book;
$book->setdb('...');
$book->setprice('...');
return $book;
});
 
//注入依赖
$book = Ioc::resolve('book');
&#63;>

Copy after login

The above is the understanding of PHP dependency injection and inversion of control. I hope it will be helpful for everyone to learn PHP programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1125883.htmlTechArticleUnderstand php dependency injection and inversion of control, php dependency injection inversion To understand php dependency injection and inversion of control Two concepts, you must understand the following issues: DI——Dependency Inject...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template