HomePHP The Dependency Injection Design Pattern in PHP 5
The Dependency Injection Design Pattern in PHP 5
In this first part of a six-part series, I introduce you to the dependency injection design pattern and its use with MySQL. Specifically, I create a typical scenario where one persistent class needs the functionality of its dependency, in this case a database handler, to gain access to a MySQL table.
Without a doubt, design patterns are one of the big pillars of software development that allow you to build high-quality desktop and web applications through well-trusted solutions. A solid understanding of basic concepts such as inheritance and polymorphism, in conjunction with a respectable knowledge of the most popular design patterns, can be of great help in developing professional web-based programs.
Naturally, some design patterns are harder to master than others. A few of them, however, are remarkably simple to implement in real-world conditions, and their benefits can be really enormous.
In the particular case of PHP 5, one of easiest patterns that can be applied to improve the quality of object-oriented applications is one called Dependency Injection, even though it’s not as well known as others. As its name suggests, the Dependency Injection pattern permits you to define how a given class is going to accept its dependencies, or in other words, the way that the instances that a class needs to work will be injected into its internals.
To clarify a bit further, I’m going to cite a typical example that will be familiar to you. Say there’s a model class that needs to take in an instance of a database handler to perform queries against its associated database table. In a case like this, the database handler would obviously be a dependency of the model, and it could be passed in to the model’s environment either via the constructor, or via a setter method.
This would be a basic – yet realistic -- example, where the Dependency Injection pattern is applied to promote encapsulation. Logically, this pattern can be implemented in several ways. In this series of articles I’m going to cover only some of them, including naturally the most relevant ones. In addition, I plan to touch superficially the construction of dependency injection containers, a subject that itself deserves an in-depth look.
Now, it’s time to leave the theory the drives the Dependency Injection pattern behind and start learning how to apply it in PHP 5-driven environments. Let’s get started!