HomePHP Page 4 - Using Database Objects with Factory Methods
The factory method in action - PHP
In this fourth part of a six-part series on implementing factory methods in PHP 5, I show how a simple factory method can improve the efficiency of a sample database-driven application when a database handler is utilized by multiple objects. In this specific case, the method returns Singletons of the database handler, which is a significant enhancement.
Now that you hopefully grasped how the two sample classes defined in the previous segment are capable of interacting with each other, itís time to set up an example that shows them in action. Therefore, I suggest you look at the following script. It demonstrates how to create two persistent user objects that share the same database handler, thanks to the functionality of the factory method. Here it is:
// create first user object
$user1 = new User();
$user1->name = 'Susan Norton';
$user1->email = 'firstname.lastname@example.org';
// create second user object
$user2 = new User();
$user2->name = 'Mary Smith';
$user2->email = 'email@example.com';
Even though this code fragment looks similar to the one shown in the first section of this tutorial, the truth is that things are quite different behind the scenes. In that first case, each user object created a different instance of the database handler, while in this last example, only one instance of it is shared between those objects.
While this code sample is rather trivial in its nature, it demonstrates how the definition of a factory method that returns Singletons may help to implement a more effective relationship between some objects and the respective dependencies.
Finally, if you wish to tweak all of the examples included in this article, either for educational purposes or just for fun, feel free to do that. The experience will be instructive, trust me.
In this fourth installment of the series, I showed how a simple factory method can improve the efficiency of a sample database-driven application when a database handler is utilized by multiple objects. In this specific case, the method in question returned Singletons of the database handler, which is a significant enhancement.
Nevertheless, this example application in its current version is far from being really efficient. The constructor of the previous ďUserĒ class is still responsible for creating an instance of the database handler, which you know is a bad thing. Thus, in the next tutorial Iím going to decouple this process, so the involved classes will be able to work more independently.