HomePHP Using a Model Class with the Dependency Injection Design Pattern
Using a Model Class with the Dependency Injection Design Pattern
Welcome to the fourth part of a series on applying the dependency injection design pattern in PHP 5. Through a strong hands-on approach, this series teaches you several methodologies that you can use for taking advantage of the functionality given by this simple yet powerful design pattern. It shows you how to build classes that follow the schema imposed by the Inversion of Control software design principle.
And now that you've been introduced to the goal of this series, itís time to review the topics that were covered in the last article. In that tutorial I explained how to apply the dependency injection pattern with a couple of sample classes.
In this concrete example, the first of these classes was a basic MySQL database handler, while the latter was a persistent class, which required of the functionality of the first to work properly. Asides from outlining how the classes interacted with each other, the most relevant detail is the fact that the persistent class implemented a simple setter method for inputting an instance of the database handler into its internals.
This kind of relationship between classes, where a setter method is employed to inject an object into the inside of another one, is commonly know as ďdependency injection by setter method.Ē Itís another way of implementing the dependency injection pattern.
However, this pattern can be used in multiple scenarios and environments, even though so far itís been overlooked by some developers. In reality, the pattern plays a relevant role in applications that use the Model-View-Controller paradigm, which as you know is extremely popular these days.
Therefore, in the next few lines Iím going to show you how to apply dependency injection within a model class that will handle a MySQL table containing records on some fictional users.
Want to see how to combine the functionality of the MVC and the dependency injection patterns in one single PHP 5 program? Then begin reading right now!