HomePHP Injecting Objects by Constructor with the Dependency Injection Pattern
Injecting Objects by Constructor with the Dependency Injection Pattern
While not being as widely known as other design patterns such as Factory, Singleton or Active Record, the Dependency Injection pattern provides both programmers and web developers with a well-structured solution that allows them to solve issues that arise when an object needs the functionality of another one (hence the dependency) to work as expected. This is the second part of a six-part series that shows you how to apply this pattern.
In simple terms, when this pattern is applied, the dependency is directly injected (hence its name), either through the constructor of the receiver object or via a setter method. In both cases, the implementation of the pattern goes hand in hand with a concept of software engineering called Inversion of Control. This concept states that the context in which an object exists is responsible for providing it with its dependencies, and not the inverse situation (the term “inversion” makes sense here).
Obviously, in a scenario where objects are merely passive entities that expect to receive the dependencies that they need to function properly from the outer world, putting injection dependency into practice is a no-brainer process. This is particularly true in the case of PHP 5 where its type hinting feature helps to achieve this task in a simple manner.
If you've already read the first part of this series, then you should have a vague idea of how to implement the dependency injection pattern in PHP 5. In that tutorial I developed a sample application composed of two building blocks: a rudimentary MySQL abstraction class, and a persistent class that required the functionality of the first for saving and retrieving its properties from a database table.
In this specific example, persistent objects were entirely responsible for creating the database handler that they needed to work, which happens to contradict the Inversion of Control principle. This is not a desirable effect.
Thus, in this second part of the series I’m going to discuss how to use the dependency injection pattern to solve the aforementioned issue. Now, it’s example time, so let’s move on and start writing some functional PHP 5 code!