HomePHP Page 4 - Implementing Factory Methods in PHP 5
Factoring web form element objects - PHP
If you’ve ever developed desktop applications using mature object-oriented languages like C++ and Java, then it’s possible that you’ve found yourself saying a few funny phrases such as “I need to implement a factory method within this class,” or in the worst case: “this class needs to implement a factory method, but I don’t have a single clue about how to do that.” Surprisingly, you can implement these factory methods pretty quickly and easily in PHP 5, as this six-part series will show you.
Undoubtedly, the best way to understand how the previous form element factory class works is by looking at an example. So, with that idea in mind, below I coded a small script that first spawns two form element objects, and then calls the "render()” method of these objects to display the corresponding HTML elements on screen. Take a look:
This basic example shows how easy it is to define a factory method in PHP 5, which in this particular case builds a couple of web form element objects. But, before I hear your loud complaints, it’s important to note that the use of the factory method and its originating class is rather poor, since an instance of this class has been previously created, which is completely unnecessary.
However, this issue will be partially addressed in the next part of the series. So, for the moment feel free to edit all of the code samples included in this tutorial, which will help you build a more solid background in defining factory methods in PHP 5.
Final thoughts
In this introductory installment of the series, I provided you with a quick overview of implementing factory methods with PHP 5. In this specific case, I went through the development of a basic factory class, which was tasked with creating web form element objects, thus making it much easier to generate HTML forms in a dynamic way.
However, as you may have noticed, this factory class has a serious drawback. It calls its “factory” method in the object context, which means that an instance of the class was previously created. This instantiation process isn’t necessary at all, since the purpose of the class was to build form element objects, without dealing with its own instances.
Thus, in the next part of the series I’m going to modify the definition of this factory class so it can return only singletons to client code.