As I said in the preceding segment, I’d like to finish this tutorial by showing you how the refactored version of the previous “UserModel” class can be used for inserting, updating and deleting records from its associated “users” MySQL table. To do that, I coded a short script that shows how neatly dependency injection works when using the model’s setter method. Here’s the corresponding example code: // create new instance of MySQL class $db = new MySQL('host', 'user', 'password', 'database'); $userModel = new UserModel(); // inject MySQL instance in the model via its setter method $userModel->setDatabaseHandler($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); As seen above, once an instance of the “MySQL” class has been properly created, it’s injected into the internals of the user model via the “setDataBaseHandler()” method, so it can perform CRUD operations against its targeted table. Again, it’s fair to point out that the approach that you’ll use to apply dependency injection within your own PHP 5-based applications will depend on certain factors, including the number of dependencies required by class, the application's structure, and finally, your personal coding preferences. Final thoughtsIn this fifth episode of the series, I explored the implementation of the dependency injection pattern by using a simple setter method within a model class. As you were able to see for yourself, this approach is very easy to follow, so I think you shouldn’t have major problems putting it into practice. In addition, it’s worthwhile to say that another common case where dependency injection shines is when building polymorph objects via interfaces. That sounds hard to grasp, right? Well, fear not, because in the following article I’m going to teach you how to apply this useful concept to building a couple of database drivers in PHP 5. Don’t miss the next tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|