HomePHP Using Singletons with Factory Methods in PHP 5
Using Singletons with Factory Methods in PHP 5
In this second installment of a six-part series on implementing the factory pattern in PHP 5, I explain how to build an improved version of a factory class that returns Singletons of itself to client code.
While this may sound like a clichť, the truth is that building factory methods in PHP 5 is a straightforward process that only requires an intermediate background in working with objects and classes. After all, a factory method is merely a regular class method that returns, when possible, one or more objects to client code -- or expressed in other terms, itís a concrete implementation of the Factory design pattern.
In reality, learning the basics of factory methods is one of those things that every PHP developer must tackle sooner or later. They're used very frequently in the development of object-oriented web applications, which makes it practically impossible not to deal directly with them at some point.
Of course, if you already went through the introductory part of this series, then you have a pretty clear idea of how to create factory methods using PHP 5. In that tutorial I demonstrated how to create a simple factory class which could spawn a couple of web form element objects for rendering on screen a few basic HTML input boxes and text areas.
However, this example factory class has a serious down side. In its current version itís necessary to create an instance of it to dynamically call its factory method, and therefore spawn the mentioned web form element objects. Actually, this is considered a bad thing in terms of programming habits, because in this particular case the goal of the factory class is to build other objects, other than its own..so whatís the point in dealing with instances of it? Thatís pretty useless.
To address only partially the issue described above, in this second chapter of the series Iím going to introduce some subtle changes into the definition of this factory class, so it can return Singletons of it to client code. This at least will make sure that only one instance of it will be created during the execution of a given script.
Now, letís and see how to translate the previous concepts to fully-functional PHP 5 code. Letís go!