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 ...

Get Magento 2 Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.