Code Snippets

Example of Dependency Injection

Consider the following example:

class ChairBuilder { private $hammer; private $nail; private $wood; public function __construct() { $this->hammer = new Hammer(); $this->nail = new Nail(); $this->wood = new Wood(); } public function buildChair() { // build the chair } }

 

Cleaning up the code:

class ChairBuilder { private $hammer; private $nail; private $wood; public function __construct(Hammer $hammer, Nail $nail, Wood $wood) { $this->hammer = $hammer; $this->nail = $nail; $this->wood = $wood; } public function buildChair() { // build the chair } }

Now taking one step further by generalizing the code:

interface StrikingToolInterface{} interface JoiningToolInterface{} interface BuildingMaterialInterface{} class ChairBuilder { private $strikingTool; private $joiningTool; private $buildingMaterial; public function __construct(StrikingToolInterface $strikingTool, JoiningToolInterface $joiningTool, BuildingMaterialInterface $buildingMaterial) { $this->strikingTool = $strikingTool; $this->joiningTool = $joiningTool; $this->buildingMaterial = $buildingMaterial; } public function buildChair() { // build the chair } }

For more information, refer to this blog post

Resource Tags: