What is dependency injection?

一个新手
Release: 2023-03-16 18:58:01
Original
3687 people have browsed it

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();
}
Copy after login

2. Different types of sending implement this interface


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


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

3.


   __construct( ->_mailObj =  
        ->_mailObj->send();
Copy after login


<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>
Copy after login

The above is the detailed content of What is dependency injection?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!