HomePHP Page 4 - Creating Objects Dynamically with Factory Methods
Calling a factory method out of the object scope - PHP
Welcome to the third part of a series that shows you how to implement factory methods in PHP 5. Made up of six tutorials, this series uses numerous friendly code samples to illustrate how to implement the Factory and Singleton design patterns within your PHP 5-based web applications. In this way, they will be able to build objects in a truly efficient manner.
In the previous section the definition of the sample factory class was subtly modified, and its factory method was turned into a static one -- so now we need to see how this specific method can be used for creating web form element objects in a few simple steps.
Thus, below I coded a final script, which clearly demonstrates this process. Here it is:
Undeniably, the above code fragment shows the advantages of declaring the “factory()” method of the “FormElementFactory” class static, because thanks to this small modification, it’s possible to create a pair of web form element objects without having to mess with any instances of this factory class.
While the previous example is rather primitive, it demonstrates not only how to define a factory method, but how to use it properly, without getting into bad programming habits.
Finally, feel free to edit all of the code samples included in this tutorial, so you can improve your existing skills in factoring objects in PHP 5.
That’s about it for the moment. Over this third episode of the series, I demonstrated how to use a static factory method to create other objects, which in this particular case were simple representations of HTML form elements, such as text areas and input boxes.
If you reread the previous sentence, you’ll realize that this factory method was charged with creating instances of other classes. Nonetheless, it’s also possible to define factory methods that create instances of its originating class.
That will be exactly the topic that I plan to cover in the next tutorial. So, now that you’re aware of the subject of that article, you can’t miss it!