HomePHP Page 4 - Using a Model Class with the Dependency Injection Design Pattern
Performing CRUD operations with the user model class - PHP
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.
Without a doubt, the best way to understand how the sample classes shown before can be put to work together is by developing a small application that shows how to run CRUD operations against the fictional ďusersĒ MySQL table.
Provided that the corresponding definitions of these classes have been previously included either as a single file or as a set of separate dependencies, then inserting, updating and deleting users would be as simple as this:
// create new instance of MySQL class
$db = new MySQL('host', 'user', 'password', 'database');
// inject instance of MySQL in the model via its constructor
From the previous script, itís clear to see that the combined functionality of both the MVC and the dependency injection patterns can lead to coding programs that not only separate properly application logic from visual presentation, but in which their building classes are loosely coupled.
In this particular example, the database handler (or in other words, the dependency) is injected into the internals of the model via the constructor of the latter, but as you know itís possible to achieve the same result with a setter method.
Finally, I suggest that you edit some of the code samples developed in this tutorial, which hopefully will equip yourself with a better understanding of how to apply the dependency injection pattern in PHP 5.
In this fourth installment of the series, you learned how to merge the functionality of both the Model-View-Controller and the dependency injection patterns, to build a MySQL-driven application that perform CRUD operations on a ďusersĒ database table.
In this case, the dependency was passed to the model class via the constructor of the second one, but as I said before, itís also feasible to implement a setter method to accomplish this task with similar results.
This approach will be discussed in depth in the next tutorial, so you donít have any excuses to miss it!