If you’re like me, then it’s probable that you want to see how the modified version of the “User” class can be used to build a couple of persistent objects. Below I coded a script that does precisely that. Here it is: // create first user object $user1 = new User(MySQL::factory('host', 'user', 'password', 'database')); $user1->name = 'Susan Norton'; $user1->email = 'susan@domain.com';
// create second user object $user2 = new User(MySQL::factory('host', 'user', 'password', 'database')); $user2->name = 'Mary Smith'; $user2->email = 'mary@domain.com'; Without a doubt, the relationship between the “User” class and the MySQL database handler is now much more independent. As you can see, the factory method of “MySQL” is used to inject a Singleton into the constructor, which demonstrates how simple it is to implement the injection dependency pattern via a constructor method. In addition, the previous example can be streamlined even more, by coding it as follows: // create instance of MySQL class via the factory method $db = MySQL::factory('host', 'user', 'password', 'database'); // create first user object $user1 = new User($db); $user1->name = 'Susan Norton'; $user1->email = 'susan@domain.com';
// create second user object $user2 = new User($db); $user2->name = 'Mary Smith'; $user2->email = 'mary@domain.com'; There you have it. In this last case, the factory method of the “MySQL” class is called only once, and then the corresponding instance is simply inputted into the respective constructors of the persistent objects. Finally, with this example I’m finishing this fifth tutorial of the series. As always, feel free to edit all of the code samples included in this article to arm yourself with a much better background in building factory methods with PHP 5. Final thoughts That’s about it for now. Over this fifth installment of the series, I showed how the removal of a factory method inside the constructor of the class that originates persistent objects can produce a huge impact in the way that those objects handle its dependency, which in this specific case happens to be a database handler object. In the last chapter, I’m going to explain how to further improve the relationship established between the sample classes shown earlier, which surprisingly won’t require the use of a factory method. Here’s my final suggestion: don’t miss the conclusion!
blog comments powered by Disqus |
|
|
|
|
|
|
|