Despite the rather complicated-sounding nature of the phrase, building object-based forms is a really easy thing to do. With all of the form element classes already defined, as well as the “formElementFactory” class acting as a real factory that returns form objects, setting up the “formGenerator” class for displaying layout-controlled web forms is a pretty straightforward task. To test the functionality of the “formGenerator” class, I’ll show an example that builds a simple login form, comprised of “username” and “password” fields, together with the corresponding login button. Also, I’ll add some additional markup within the form, to demonstrate the control over the general layout that the class offers. So, the sample code looks like this: // define parameters for the formGenerator class As you can see, although the above snippet takes up only a few lines of code, it is actually very powerful. First, the script builds a recursive array with the name and parameters of each form object to be created. Here is the line responsible for doing this: // define parameters for the formGenerator class Then, a new “formGenerator” object is instantiated and the above array is passed to the constructor. Let’s stop briefly at this point and see what’s happening here: if we return to the definition of the class, it’s clear that only two lines are required to generate the main source code of the form, because all of the internal processing for factoring form objects is handled inside the class context. This simple concept demonstrates the real power of the factory pattern, when correctly applied. The rest of the code uses the “addFormPart()” method to roughly build a table containing the labels for each field, along with the “addElementHeader()” and “addElementFooter()” methods to wrap up form fields into a containing <table> structure. Finally, the complete (X)HTML markup is displayed by calling the “getFormCode()” method, like this: echo $fg->getFormCode(); By this point, you’ve been provided with the required background to use some design patterns in order to build web forms based on an object-oriented method. Definitely, repetitive and boring tasks involved in the development of web programs such as form generation, can be easily turned into flexible processes by conceiving them as an issue feasible to be solved through the object-oriented paradigm. To wrap up, for those developers who want to have available “in one place” all the source code developed for PHP5, I’ll offer a list of each class used to build object-based forms.
blog comments powered by Disqus |