Home > Backend Development > PHP Tutorial > Three ways of dependency injection in php

Three ways of dependency injection in php

angryTom
Release: 2023-04-07 08:54:01
Original
8137 people have browsed it

Three ways of dependency injection in php

Inversion of Control (IoC) is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. The most common method is called Dependency Injection (DI). Below we will introduce to you the three methods of dependency injection in PHP.

Recommended tutorial: PHP video tutorial

##1. Constructor injection

Inject the dependent object into the dependent object through the parameters of the constructor, and inject it when initializing the object.

Advantages:

After the object initialization is completed, the usable object can be obtained.

Disadvantages:

 ●When there are many objects that need to be injected, the constructor parameter list will be very long;

 ●Not flexible enough. If there are multiple injection methods, and each method only needs to inject a few specified dependencies, then multiple overloaded constructors need to be provided, which is troublesome

2. Setter method injection

IoC Service Provider injects the dependent object into the dependent class by calling the setter function provided by the member variable.

Advantages:

Flexible. Required objects can be selectively injected.

Disadvantages:

After the dependent object is initialized, it cannot be used because the dependent object has not been injected yet.

3. Interface injection

The dependent class must implement the specified interface, and then implement a function in the interface, which is used for dependency injection. The parameter of this function is the object to be injected.

Advantages

In interface injection, the name of the interface and the name of the function are not important, as long as the parameters of the function are the type of the object to be injected.

Disadvantages

The intrusion is too strong and is not recommended.

PS: What is an intrusion line?

If class A wants to use a function provided by others, if in order to use this function, it needs to add additional code to its own class, this is intrusive.

The above is the detailed content of Three ways of dependency injection in php. 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