HomePHP Page 4 - Dependency Injection: Using a Setter Method within a Model
Performing CRUD operations on user-related records - PHP
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.
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
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.
In 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.