HomePHP Page 3 - The Singleton and Factory Patterns in PHP: Building object-oriented forms
Object-oriented forms: applying the Factory pattern to a real application - PHP
Experienced PHP programmers know that web development problems are often tackled by using widely known design patterns within the context of an application. This article is the first in a series that will demonstrate how the Singleton and Factory patterns can be implemented in a real-world application.
As you know, there are many approaches to building regular web forms. Commonly, we plan carefully what kind of data needs to be collected from users, then open our editor and write some (X)HTML code to display the proper form, including a few text boxes, radio buttons and so forth.
While this method may be quick and simple for implementing on small websites, when an application grows significantly in size, an object-based method is often much more efficient. If the program will use numerous forms for collecting user data, the form creation process might be reduced to something as simple as instantiating some form element objects and deciding the best layout for them.
The Factory pattern is very powerful and flexible, since it allows you to separate object instantiation from the rest of the client code. Generally speaking, this pattern is implemented through a class that accepts one or more parameters (inputs), and based on those parameters, determines what object to instantiate.
Due to the intrinsic power of the Factory pattern, I'm going to apply it in a concrete situation: the implementation of a "form element factory" that will take care of factoring each form component. Doing so, creation of forms can be noticeably simplified and translated into better code portability.
At this time, maybe you're wondering how the Singleton pattern will be applied. Well, I said before that the Factory pattern allows us to easily develop a form element factory. However, it's highly desirable to work with only a single instance of the factory across the whole application. Thus, the Singleton pattern will be used for having a single object instantiation.
But I'm getting ahead of myself. As you know, a long journey begins with one single step, so let's expose some previous methodologies for implementing object-based forms before jumping into the application of design patterns.