Home  >  Article  >  Backend Development  >  What is dependency injection?

What is dependency injection?

一个新手
一个新手Original
2017-10-25 13:16:573694browse

Dependency Inversion (DIP): DIP is a design idea. In traditional software design, the upper layer code depends on the lower layer. When the lower layer code changes, the upper layer code will also change. The code is not easy to maintain, and DIP design The idea requires defining the upper layer interface and the lower layer implementing this interface, thereby reducing the degree of coupling.

Inversion of Control (IOC): IOC is a specific idea of ​​​​DIP, which leaves the lower layer on which the upper layer depends to be implemented by a third party. In other words, it is the initiative to obtain the required external resource C in category 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.

Dependency Injection (DI): DI is a design pattern of IOC that moves the instantiation of a class that depends on another class to the external implementation of the class.

Dependency injection is implemented:

1. Define an interface or abstract class (this is an example of sending emails)


interface Mail{    public function send();
}

2. Different types of sending implement this interface


class Email implements Mail()
{    public function send()
    {        //发送Email    }
}


class  SmsMail implements Mail()
{    public function send()
    {        //发送短信    }
}

3.


   __construct( ->_mailObj =  
        ->_mailObj->send();


<span style="color: #008000"><br/>$reg = new Register();<br/>$emailObj = new Email();<br/>$smsObj = new SmsMail();<br/><br/>$reg->doRegister($emailObj);//使用email发送<br/>$reg->doRegister($smsObj);//使用短信发送<br/></span>

The above is the detailed content of What is dependency injection?. 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