Chapter 6. Replace new with Dependency Injection

Even though we have removed all global calls in our classes, they are likely to retain other hidden dependencies. In particular, we are probably creating new object instances in inappropriate locations, tightly coupling the classes together. These things make it much harder to write tests and to see what the internal dependencies are.

Embedded instantiation

After converting the global calls in a hypothetical ItemsGateway class, we might have something like this:

classes/ItemsGateway.php 1 <?php 2 class ItemsGateway 3 { 4 protected $db_host; 5 protected $db_user; 6 protected $db_pass; 7 protected $db; 8 9 public function __construct($db_host, $db_user, $db_pass) 10 { 11 $this->db_host = $db_host; 12 ...

Get Modernizing Legacy Applications in PHP 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.