Chapter 5. Using the Dependency Injection
Dependency injection is a software design pattern via which one or more dependencies are injected or passed by reference into an object. What this exactly means on a practical level is shown in the following two simple examples:
public function getTotalCustomers() { $database = new \PDO( … ); $statement = $database->query('SELECT …'); return $statement->fetchColumn(); }
Here, you will see a simplified PHP example, where the $database
object is created in the getTotalCustomers
method. This means that the dependency on the database object is being locked in an object instance method. This makes for tight coupling, which has several disadvantages such as reduced reusability and a possible system-wide effect caused by changes made to some parts of the code.
A solution to this problem is to avoid methods with these sorts of dependencies by injecting a dependency into a method, as follows:
public function...