In the previous section you saw how easy it is to use a setter method for passing the MySQL database handler to the internals of the persistent “User” class. Nonetheless, the best way to understand this process is by example, right? Thus, below I coded one for you that demonstrates how to create two persistent objects in a snap.
Take a look at the following code fragment:
// create instance of MySQL class
$db = new MySQL('host', 'user', 'password', 'database');
// create first user object
$user1 = new User();
$user1->name = 'Alejandro Gervasio';
$user1->email = 'email@example.com';
// create second user object
$user2 = new User();
$user2->name = 'Mary Smith';
$user2->email = 'firstname.lastname@example.org';
Here you have it. Thanks to the implementation of dependency injection via a setter method, it’s extremely simple to build two trivial persistent objects. Also, it’s quite possible that you find the approach that utilizes a constructor a little bit cleaner, but when a class requires multiple dependencies, probably a setter method is a better option.
Finally, feel free to tweak all of the code samples shown in this article, so you can get a more intimate knowledge of applying the dependency injection pattern by means of a setter method.
In this third article of the series, you hopefully learned how to implement the dependency injection pattern by using a simple setter method. As you saw for yourself, this process is very similar to the one that uses a constructor, so in theory you shouldn’t have major problems understanding its driving logic.
In the next chapter, things will get even more interesting. I plan to demonstrate how to use dependency injection within a PHP 5-based application that works with the popular Model-View-Controller pattern.
Don’t miss the forthcoming article!
blog comments powered by Disqus