Dependency Injection
Explore dependency injection in PHP to reduce tight coupling between classes. Understand how passing dependencies externally enhances code flexibility, supports the single responsibility principle, and simplifies unit testing. Learn to inject different driver types into a Car class without modifying its code.
We'll cover the following...
One of the less understood subjects for fresh PHP programmers is that of dependency injection. This lesson will explain the subject in the simplest way possible by first explaining the problem and then showing how to solve it.
The problem: Tight coupling between classes
When class A cannot do its job without class B, we say that class A is dependent on class B. In order to perform this dependency, many programmers create the object from class B in the constructor of class A.
For example, say we have the classes Car and HumanDriver. The Car class is dependent on the HumanDriver class, so we might be tempted to create the object from the HumanDriver class in the constructor of the Car class.
Although ...