HomePHP The Role of Interfaces in Applying the Dependency Injection Design Pattern
The Role of Interfaces in Applying the Dependency Injection Design Pattern
Welcome to the sixth part of a series covering the dependency injection pattern. In this part, I build a PHP 5-based application that can work seamlessly with MySQL and SQLite. It will feature a simple interface and a MySQL driver.
When it comes to defining the way that a PHP class is going to accept the instances that it will need to work within a given application, there’s a simple and powerful approach that allows you to achieve this goal in a truly effective way, without suffering premature hair loss.
Does this phrase ring any bells for you? Enter the dependency injection pattern, a proven programming methodology that will let you specify how one or more classes will take from their working context the dependencies (hence the pattern’s name) that they require to function properly.
In general, there are two approaches that can be used for implementing dependency injection successfully. It’s quite probable that both of them will be equally familiar to you. The first one relies on the dependency being injected via the constructor of the receiver class, while the second one accomplishes the same thing using a setter method instead.
Naturally, as with any other design pattern, the theoretical concepts that stand behind the dependency injection pattern must be backed up with a substantial amount of functional code. And that’s exactly what I attempted to do in the previous articles of this series. In those tutorials I explained how to implement the two approaches, first by using persistent objects and second, a model class, which hopefully showed that combining the functionality of the Model-View-Controller pattern and dependency injection within the same PHP 5-driven application is actually a no-brainer process.
However, there are many other scenarios where dependency injection can be used for optimizing the relationship between classes. One of the most common is when building polymorphs, or in other words, objects that are of the same type, but behave differently under certain conditions.
Very frequently, polymorphism is used in PHP 5 to develop web sites, applications, frameworks and so forth that transparently support the use of multiple database drivers. But, can this programming pillar be combined with dependency injection in a successful way? Fortunately, the answer is yes! And to prove this, in the upcoming sections I’m going to start building a basic web program that will be capable of interacting seamlessly with MySQL and SQLite, thanks to the clever use of dependency injection and interfaces altogether.
Now, it’s time to begin creating this sample database-driven application with PHP 5. Let’s get going!