ChadNomad Posted July 31, 2008 Share Posted July 31, 2008 I'm writing a class (or trying) to make forms quicker to produce. Heres an example function: function input($type, $class, $value, $newline) { if (!empty($type)) { $html .= "type=".$type.self::space; } if (!empty($class)) { $html .= "class=".$class.self::space; } if (!empty($value)) { $html .= "value=".$value.self::space; } if (!empty($newline)) { $html .= self::lineBreak; } $this->output = '<input '.$html.' />'.self::newLine; echo $this->output; } What would be a better approach to all the if statements or is that perfectly fine? Thanks Quote Link to comment Share on other sites More sharing options...
mbeals Posted July 31, 2008 Share Posted July 31, 2008 make each tag type it's own class. so for an input tag you could use this: <?php class input { private $options = array(); function __construct($name = NULL, $type = NULL){ if($type) $name = array('name' => $name, 'type' => $type); if(is_array($name)) $this->fill($name); } function fill($stuff){ foreach($stuff as $option=>$value) $this->options[$option] = $value; } function setOption($option,$value){ $this->options[$option] = $value; } ////insert more add/modify methods here function getHTML(){ $html = '<input'; foreach($this->options as $option=>$value) $html .= " $option='$value'"; $html .= ">"; return $html; } function printHTML(){ echo $this->getHTML(); } } ?> This class keeps all options (everything in the form of something="value") in one array. This is just a prototype... I wrote it off the top of my head and rather quickly, so it could stand for some cleaning up. When you create the object, you can either just define the name and type of the input like: $foo = new input('name', 'type'); or pass an array of options to it: $options = array('name' => 'bar', 'type' =>'text', 'class' => 'someclass'); $foo = new input($options); Passing no arguments will just create an empty object. Additional options are set and unset with fill() in array form, or by setOption() like: $foo->setOption('options', 'value'); getHTML() returns the html string wile printHTML() echos it out I have a select class similar to this that is exceedingly useful. I event went so far as to write a tag class that will build any html tag given type, options (within the opening tag) and the contents (between the tags). If you go that route, the above code would simplify even more. Quote Link to comment Share on other sites More sharing options...
DarkWater Posted July 31, 2008 Share Posted July 31, 2008 You could also make all of those classes implement an Element interface or something so that you can then just make an ElementFactory and use any element regardless of which one it actually is. <3 Polymorphism Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.