What is dependency injection?

Source: Internet
Author: User
Dependency inversion (DIP): Dip is a design idea, in the traditional software design, the upper layer of code relies on the lower layer, when the underlying code changes, the upper code will be changed, the code is difficult to maintain, and the DIP design concept requires the definition of the upper interface, the lower layer to implement this interface, thereby reducing the coupling degree.

Inversion of Control (IOC): The IOC is a specific approach to dip, which will be implemented by third parties by the lower layer on which it relies. That is, to proactively get the required external resource C in Class A, which is referred to as positive. So what's the reverse? is a class no longer master to acquire C, but passively wait, waiting for the Ioc/di container to get an instance of C, and then injected into the reverse of the Class A.

Dependency Injection (DI):D i is a design pattern for the IOC that moves the instantiation of a class from another class to an external implementation of the class.

Dependency injection is the implementation:

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


Interface mail{public    function Send ();}

2. Different types of send implement this interface


Class Email implements Mail () {public    function send ()    {        //Send email    }}


Class  Smsmail implements Mail () {public    function send ()    {        //Send SMS    }}

3.


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



$reg = new Register ();
$EMAILOBJ = new Email ();
$SMSOBJ = new Smsmail ();

$reg->doregister ($EMAILOBJ);//Use email to send
$reg->doregister ($SMSOBJ);//Send Using SMS

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.