HomePHP Dependency Injection: Using a Setter Method within a Model
Dependency Injection: Using a Setter Method within a Model
In this fifth part of a six-part series on the dependency injection pattern, I explore the implementation of the pattern by using a simple setter method within a model class. You'll see that this approach is very easy to follow.
While not as widely known as other popular design patterns like Singleton and Factory, the dependency injection pattern is a powerful programming methodology that allows you to define the way that one given class is going to accept additional objects that it requires to work as expected.
In the case of PHP 5, there are two major trends that most developers stick to when it comes to implementing dependency injection within a certain application: the first one relies on injecting the dependency of a class via its constructor, while the second approach does this, but by means of a setter method instead. Of course, both approaches use aggregation to deal with a class’s dependency, since in this case, composition contradicts the schema imposed by the Inversion of Control principle.
All of these buzzwords should be pretty familiar to you at this point, because over the course of the tutorials that preceded this one I explained how to apply the dependency injection pattern. If you go back to the previous part of this series, then you’ll recall that I left off discussing how to use the “injection by constructor” approach with a couple of basic classes.
In this specific example, the first of these classes was a simple MySQL handler, while the second one was a model class that required the functionality of the first to interact with a predefined MySQL table. This fictional scenario showed that it’s very easy to combine the power of dependency injection with the benefits of the Model-View-Controller pattern within a single application.
However, as I said a moment ago, dependency injection can also be achieved with a setter method. So, in this installment I’m going to explain how to use this approach with the pair of sample classes previously mentioned.
Want to see how this will be done? Then begin reading!