Chapter 5: Disco with Design Patterns: A Fresh Look at Dependency Injection
by Reza Lavaryan
Dependency Injection is all about code reusability. It's a design pattern aiming to make high-level code reusable, by separating the object creation / configuration from usage.
Consider the following code:
<?php
class Test {
protected $dbh;
public function __construct(\PDO $dbh)
{
$this->dbh = $dbh;
}
}
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$test = new Test($dbh)
As you can see, instead of creating the PDO object inside the class, we create it outside of the class and pass it in as a dependency - via the constructor method. This way, we can use the driver of our choice, instead of having to to use the driver defined ...
Get Better PHP Development 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.