Expressed in simple terms, the web form helper class that I plan to build in the following lines will be pretty basic. It will implement some simple methods aimed at rendering different form elements, including different types of input boxes, radio buttons, text areas and so forth. So far, nothing unexpected, right? In most cases, the methods of this helper will be called statically to prevent an unnecessary instantiation of the originating class. However, similarly to other classes developed before, this one will implement a “getInstance()” method that will return a Singleton instance of the class in question. Now that I have outlined how the form helper is going to work, please take a look at its partial source code, which looks as simple as this: class Form { private static $instance = NULL;
// get Singleton instance of Form class public static function getInstance() { if (self::$instance === NULL) { self::$instance = new self; } return self::$instance; }
// render <form> opening tag public static function open(array $attributes) { $html = '<form'; if (!empty($attributes)) { foreach ($attributes as $attribute => $value) { if (in_array($attribute, array('action', 'method', 'id', 'class', 'enctype')) and !empty($value)) { // assign default value to 'method' attribute if ($attribute === 'method' and ($value !== 'post' or $value !== 'get')) { $value = 'post'; } $html .= ' ' . $attribute . '="' . $value . '"'; } } } return $html . '>'; }
// render </form> closing tag public static function close() { return '</form>'; } }// End Form class Apart from the implementation of the aforementioned “getInstance()” method that returns a Singleton object, which may look a bit tricky, the rest of the logic of the above “Form” class should be extremely easy to follow for you. As shown above, the class defines just a couple of methods for rendering the opening and closing tags of an HTML form. Period. These methods have been declared static, meaning that there’s no need to create an instance of the helper to invoke them directly. Also, it must be admitted that the class in its current incarnation could be largely improved, to make it more functional. But in keeping with the requirements of this particular project, it’ll be kept simple. So far, so good, right? At this moment, I’m sure that you've grasped how the previous “Form” class does its thing, so it’s time to add more methods to it. In the last segment of this tutorial I’m going to code one that will be tasked with rendering some common form input elements. To learn how this new method will be implemented, go ahead and read the following section. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|