Dependency Injection
Learn about the tight coupling problem and how to solve it using dependency injection.
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.
<?phpclass HumanDriver {// Method to return the driver namepublic function sayYourName($name) {return $name;}}// Car is dependent on HumanDriverclass Car {protected $driver;// We create the driver object in the constructor,// and use this object to populate the $driver propertypublic function __construct(){$this -> driver = new HumanDriver();}// A getter method that returns the driver object// from within the car objectpublic function getDriver(){return $this -> driver;}}?>
Although ...