HomePHP Page 4 - Inheritance and Polymorphism in PHP: Building a Form Generator - Part III
Implementing the Form Generator: take two - PHP
In the last part of this three-part series of articles, we will find out how to improve the form generator we created in part II by learning about Polymorphism and adding it to the mix.
With the pillars of Inheritance and Polymorphism playing in our favor, it's time to define the final version of our so-called form generator. Since each form element subclass derived from the base class exposes a specific "generateHTML()" method, the process for implementing Polymorphism is fairly straightforward. All that we need to do is get rid of any "switch" statements and take advantage of the capabilities present in the subclasses. Doing so, our revamped form generator should be coded in the following way:
// include required class file
require_once('formclasses.php');
// instantiate derived inputText objects from super class formObject
Whew! The code definitely looks a lot better. We simply instantiated a set of three of text input objects, a checkbox, and a select menu. Then we added a text area and, finally, a regular submit button.
With all of the form objects properly defined, we've created an array structure and looped through the objects, just invoking the "generateHTML()" method in each iteration. In this way we generated the complete HTML form. Simple enough, eh?
As you can see, this method is by far more efficient and maintainable. With a few changes on the base class, all of the subclasses would automatically inherit the new properties or methods. In a similar way, if we need to add another form element to the form generator, just adding the corresponding subclass, we get the job done nicely.
And that's all for now…oh, wait a minute! A few final disclaimers are needed. Taking a deeper look at the code for each form object subclass, we clearly see that they offer limited possibilities for defining the overall layout for different form elements. However, this could be changed, easily adding an ID property to tie a style, or redefining the "generateHTML()" method, for major layout flexibility. I've shown a basic form layout. Now you can take the code, reuse it, expand it, or create your own version of it. The possibilities are vast.
My final observation points to application performance. Since we're working possibly with numerous objects here, in slow systems this might cause an extra overload for the Web server. Having said that, we're finally done. For those who want to include this solution in Web applications, we'll list the complete source code, including the base class and its subclasses.