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 $userModel = new UserModel($db); // add new user $userModel->save(array('fname' => 'Alejandro', 'lname' => 'Gervasio', 'email' => 'alejandro@domain.com')); // update existing user $userModel->save(array('fname' => 'Mary', 'lname' => 'Wilson', 'email' => 'mary@domain.com'), 1); // delete existing user $userModel->delete(1); 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. Final thoughts 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!
blog comments powered by Disqus |
|
|
|
|
|
|
|