Home >PHP Framework >ThinkPHP >ThinkPHP container inversion of control and dependency injection
The name Dependency Injection Inversion of Control sounds confusing. After reading this article, you will know what it is.
In fact, these two refer to A thing is just a programming idea, don't think it is so difficult to understand and lofty.
So what is a container? To understand it directly, a container is a thing that holds things. In programming, our common variables and object properties are all containers. What can be contained in a container depends entirely on the definition of the container.
However, what we are discussing now is another kind of container. It stores neither text nor values, but objects, classes, and interfaces. Through this kind of container, many advanced functions can be realized. The most commonly used one is code. decoupling and dependency injection.
So why are there two concepts, why do we talk about inversion of control and dependency injection! As mentioned above, they actually refer to the same thing, but they are described from different angles.
Just as you are your father’s son, you are still your grandfather’s grandson. Both son and grandson refer to the same person. It's just a matter of looking at the problem from a different perspective.
Inversion of Control
is to look at the problem from the perspective of the container. The container controls the application, and the container reversely injects the external information required by the application into the application. resource.
Dependency Injection
looks at the problem from the perspective of the application. The application relies on the container to create and inject the external resources it needs.
Function
It is mainly used to reduce the degree of coupling between codes.
Effectively separate objects and external resources required by the application.
The following two pictures can clearly explain the problem
Let me give you a simple case
Define two classes as Person and Car, instance in Person and call the pay method in Car.
Then call it in the controller, and the printed result must be the 123 returned by Car, so this will not be printed.
At this time we modify the code, pass the Car class directly to the Person class, and use it directly in the Person class The passed object is used to call the corresponding method.
This is just a simple implementation process. In order to pave the way for the reading framework container code, the container injection in the framework will be explained in detail later.
Persistence in learning, persistence in blogging, and persistence in sharing are the beliefs that Kaka has always adhered to since its beginning. I hope that Kaka’s articles on the huge Internet can bring you a little bit of help. I’m Kaka, see you next time.
The above is the detailed content of ThinkPHP container inversion of control and dependency injection. For more information, please follow other related articles on the PHP Chinese website!