I’ve been working on this Form class and I thought I’d share what I have so far. At this point I have two classes, a base Tag class and an Input class that extends the Tag class. I expect that I’ll create child classes for the various input devices such as radio buttons, checkboxes, and select. These child classes will get a lot more functionality such as error checking. At this point I don’t see a need to create classes for tags that don’t send input to the server.
BTW, func_num_args() and func_get_arg() are really useful when you have an indeterminate number of arguments. Here are my two classes:
class Tag {
protected $tag;
protected $attributes = array();
protected $content = array();
protected $xhtml;
public function __construct($tag, $xhtml = FALSE) {
$this->tag = $tag;
$this->xhtml = $xhtml;
}
public function setAttribute($name, $value) {
$this->attributes[] = array($name, $value);
}
public function setContent() {
$i = 0;
while ($i < func_num_args()) {
$this->content[] = func_get_arg($i++);
}
}
public function render() {
$result = "<{$this->tag}";
if (is_array($this->attributes)) {
foreach ($this->attributes AS $pair) {
$result .= " {$pair[0]}='{$pair[1]}'";
}
}
$result .= ">\
";
foreach($this->content AS $content) {
$isContent = TRUE;
if (is_object ($content)) {
$result .= $content->render();
} else {
if ($content != '') {
$result .= "{$content} \
";
} else {
$isContent = FALSE;
}
}
}
if ($isContent) {
$result .= "</{$this->tag}>\
";
}
return $result;
}
}
class Input extends Tag {
public function __construct($type, $name = '', $value = '') {
$this->tag = 'input';
$this->attributes[] = array('type', $type);
$this->attributes[] = array('name', $name);
$this->attributes[] = array('value', $value);
}
}
Using this code:
$br = new Tag('br');
$month = new Input('text', 'month', $_POST['month']);
$month->setAttribute('size', '2');
$day = new Input('text', 'day', $_POST['day']);
$day->setAttribute('size', '2');
$year = new Input('text', 'year', $_POST['year']);
$year->setAttribute('size', '4');
$submit = new Input('submit', 'submit', 'Submit');
$reset = new Input('reset', '', 'Reset');
$legend = new Tag('legend');
$legend->setContent('Action');
$fieldset = new Tag('fieldset');
$fieldset->setAttribute('style', 'width:300px;');
$fieldset->setContent($legend, $month, $day, $year, $br, $submit, $reset);
$form = new Tag('form');
$form->setAttribute('action', $_SERVER['PHP_SELF']);
$form->setAttribute('method', 'post');
$form->setContent($fieldset);
echo $form->render();
I generated the following form:
<form action='/testing/tag.php' method='post'>
<fieldset style='width:300px;'>
<legend>
Action
</legend>
<input type='text' name='month' value='' size='2'>
<input type='text' name='day' value='' size='2'>
<input type='text' name='year' value='' size='4'>
<br>
<input type='submit' name='submit' value='Submit'>
<input type='reset' name='' value='Reset'>
</fieldset>
</form>