HomePHP Using Database Objects with Factory Methods
Using Database Objects with Factory Methods
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.
As their name clearly suggests, factory methods are regular class methods whose responsibility is to fabricate objects in accordance with the requirements of a specific context. Since these methods are a concrete implementation of the homonymous design pattern, they’re used frequently in mature object-oriented languages like Java and C++. With the introduction of a highly-improved object model, they’ve become very popular in PHP 5 as well.
Since PHP 5 has a much flatter learning curve than Java and C++, defining factory methods with it is a no-brainer process that can be mastered with relative ease, even for developers whom have only an intermediate background in building web applications using the object-oriented paradigm.
So, if you’re a PHP programmer who wants to expand your existing skills and learn how to implement factory methods within your own web-based programs, then this group of articles will hopefully be the guide that you’re looking for.
Logically, if you’ve already read the three tutorials that precede this one, then you should have a solid idea of how to create simple factory methods in PHP 5. In those articles I used a variety of code samples to demonstrate how to define a basic factory class. This class was tasked with returning to client code a couple of objects that represented some common HTML form elements, such as input boxes and text areas.
Besides, this class implemented a static factory method that performed these operations in a pretty straightforward manner, without having to deal with any instances of the class in question. What else can one ask for?
Well, factory methods can be used in all sorts of clever ways, and not only for building a few web form element objects that are not especially interesting. In reality, when developing database-driven applications, one of the most common things a programmer must do is define a factory method that returns a single instance of a database connection handler, which is shared by other objects that need to have access to one or multiple tables.
Given that, in this fourth chapter of the series I’m going to create an scenario similar to the one described above. From this, you'll learn how to work with factory methods that optimize the way that certain objects interact with a database.
Ready to learn more about this juicy topic? Then start reading right now!