HomePHP Page 4 - Using Singletons with Factory Methods in PHP 5
The enhanced factory class in action - PHP
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.
As I promised in the previous section, below I coded a final example that demonstrates how to use the improved version of the “FormElementFactory” class to create a couple of web form element objects. Here’s the example in question:
// create instance of FormElementFactory class using its 'getInstance()' method
Definitely, the above code fragment looks much better than many of its predecessors. The static call to the “getInstance()” method of the factory class returns Singletons of it, which assures that only one instance of the class will be available across the entire script. The rest of the example remains the same, implying that the “factory()” method is again called dynamically, to spawn a couple of web form element objects.
While this example shows how to build a factory method that uses single instances of its originating class, it has plenty of room for improvement. If you’re anything like me, then it’s possible that you hear inside your head a little voice that whispers over and over again: "why not simply declare this factory method static?" Well, your inner voice is right! But, this process will be covered in detail in the next part of the series.
Meanwhile, feel free to tweak all of the code samples shown in this tutorial, so you can quickly start building your own factory methods with PHP 5.
Final thoughts
That’s all for the moment. In this second installment of the series, I explained how to build an improved version of a factory class that returned Singletons of itself to client code. While this approach permits you to avoid creating multiple instances of the class, the truth is that it can be implemented in a much more efficient manner.
If you closely analyze the definition of the class, then you’ll realize that it’s extremely easily to avoid its instantiation by simply declaring its “factory()” method static. So, in the next article I’m going to explore this solution in depth, in this way going one step further in building factory methods with PHP 5.