PHP Dependency Injection and control inversion, PHP injection reversal _php Tutorial

Source: Internet
Author: User

PHP Dependency Injection and control inversion, PHP injection inversion



Di--dependency Injection Dependency Injection

Ioc--inversion of Control inversion

To understand the above two concepts, it is necessary to clarify the following questions:

1. Who are the participants?

A: There are generally three-party participants, one is an object, one is a Ioc/di container, and the other is an external resource for an object. And the noun to explain, an object refers to an arbitrary, ordinary Java object; The Ioc/di container is simply a framework program used to implement the Ioc/di function, and the object's external resources refer to what the object needs, but it is obtained from outside the object, collectively referred to as resources, such as: other objects required by the object, or the file resources required by the object, etc.

2, dependence: Who depends on who? Why is it dependent?

A: An object is dependent on the Ioc/di container. Dependence is unavoidable, and in a project there are various kinds of relationships between classes, which cannot be completely independent, which forms a dependency. Traditional development is called directly when using other classes, which creates strong coupling, which is to be avoided. The dependency injection borrowing container transfers the dependent object implementation decoupling.

3, injection: Who injected into who? What exactly is injected?

A: Inject the external resources needed by the container to the object

4. Control reversal: Who Controls who? Control what? Why is it called inversion?

A: Ioc/di container control objects, mainly control the creation of object instances. Reversal is relative to the positive, then what is positive? Consider the general application, what would you do if you were to use C in a? Of course, it is directly to create a C object, that is, in class A to take the initiative to obtain the required external resource C, this situation is called forward. So what's the reverse? Is that class A no longer takes the initiative to acquire C, but passively waits, waits for the Ioc/di container to get an instance of C, and then injects the reverse into Class A.

5. Is the same concept of dependency injection and control inversion?

A: As you can see from the above, dependency injection is described from the perspective of the application, which can describe the full point of dependency injection: The application relies on the container to create and inject the external resources it needs, while control inversion is described from the container's perspective, describing the complete point: the container control application, The external resources required by the container to inject the application into the application in reverse.

Let's take a look at some of the implementations of dependency injection in the following example:

1. Constructor injection

 
  PHPclass  book {   private$db _conn;      Public function __construct ($db _conn) {       $this$db _conn;   }} 

2. Setter Injection

 
  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->setdb (new db ());
$book->setfile (new file ());
}?>

  

The code for both methods is clear, but when we need to inject a lot of dependencies, it means we have to add a lot of rows, which is more difficult to manage.

The better solution is to create a class as a container of all dependencies, where you can store, create, retrieve, and find the dependencies you need

 
  PHPclass  Ioc {   protected$db _conn;     Public Static function Make_book () {       $new _bookNew book ();        $new _book->set_db (self::$db _conn);        // ...       //...       Other dependencies inject       return$new _book;   }}

At this point, if you get a book instance, you only need to execute $newone = Ioc::makebook ();

The above is a concrete example of container, it is best not to put a specific dependency injection into the method, the use of registry registration, get get better

 PhpclassIoc {/** * @var registered dependent array*/    protected Static $registry=Array(); /** Add a resolve to the registry array * @param string $name dependent identity * @param object $resolve An anonymous function to create an instance * @return V OID*/    Public Static functionRegister$name, Closure$resolve)   {      Static::$registry[$name] =$resolve; }    /** * Returns an instance * @param string $name-dependent identity * @return Mixed*/    Public Static functionResolve$name)   {       if(Static:: Registered ($name) )       {          $name=Static::$registry[$name]; return $name(); }       Throw New Exception(' Nothing registered with that name, fool. '); }   /** * Query Whether a dependent instance exists * @param string $name ID * @return BOOL*/    Public Static functionRegistered ($name)   {      return array_key_exists($name,Static::$registry); }}

You can now register and inject a

 
  PHP$bookfunction() {$booknew book ; $book->setdb (' ... '); $book->setprice (' ... '); return $book  // inject dependent $book = ioc::resolve (' book ');? >

Reference: http://www.4wei.cn/archives/1002316

http://www.bkjia.com/PHPjc/1125521.html www.bkjia.com true http://www.bkjia.com/PHPjc/1125521.html techarticle PHP Dependency Injection and control inversion, PHP injection reversal didependency injection Dependency Injection iocinversion of control inversion to understand the above two concepts, you have to figure out the following ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.