HTML Helpers - Ruby Wannabes in PHP

I've gone back and forth on the idea of using ALL html generation functions to hammering it all out in a template like Smarty. Templates are nice, It sure is nice to use functions. I was looking at RoR and saw these HTML helper functions. I thought, hey I can write them in php. (Yeah to all you php hating ruby folks, this may be an effort in futility, but thinking how to implement some of these things in PHP helps me understand the concept, like my MVC articles)

Implementing just a few… Here's what I came up with:

function start_form_tag($attribs) {
     return "<form {$attribs}>";
}

function end_form_tag() {
    return "</form>";
}

function text_field($data, $name,  $attribs = "") {
    return "<input type='text' name='$name' value='{$data[$name]}' {$attribs}/>";
}

function text_area($data, $name, $attribs = "") {
    return "<textarea name='$name' $attribs>{$data[$name]}</textarea>";
}

It would be used like:

<?
// this could be retrieved from a database
$person = array();
$person['name'] = "Nola Stowe";
$person['address'] = "123 Anytown\nChicago, IL";
?>
<?=start_form_tag("action='savePerson.php'");?>
<table>
<tr>
  <td>Name</td>
  <td><?= text_field($person, 'name', "size='40'") ?> </td>
</tr>
<tr>
  <td>Address</td>
  <td><?= text_area($person, 'address', "rows='5' cols='40'"); ?></td>
</tr>
</table>
<?=end_form_tag();?>

The HTML:

<form action='savePerson.php'><table>
<tr>
  <td>Name</td>
  <td><input type='text' name='name' value='Nola Stowe' size='40'/> </td>
</tr>
<tr>
  <td>Address</td>
  <td><textarea name='address' rows='5' cols='40'>123 Anytown
Chicago, IL</textarea></td>
</tr>
</table>
</form>

Not bad. Although I believe RoR does person['name'] I can’t figure out how to get the actual “variable name” from $person … so only way to do this is to perhaps pass yet another parameter to the functions “person” and do something like this:

function text_field($data, $container, $name,  $attribs = "") {
    return "<input type='text' name='{$container}[{$name}]' value='{$data [$name]}' {$attribs}/>";
}

Then used like:

  <td><?= text_field($person, ‘person’, 'name', "size='40'") ?> </td>

But that doesn’t sit with me. I could just pass in ‘person’ then use something like:

function text_field($model, $name,  $attribs = "") {
    $data = Model::fetch($model);
    return "<input type='text' name='{$model}[{$name}]' value='{$data [$name]}' {$attribs}/>";
}	

But I’m not too sure about that either.

Any ideas?

Most likely, I will not use this in production. But I find it rather entertaining to play around with concepts such as these

Sorry, not the posting about the review of test frameworks as promised, maybe next week

Interesting Jared, can you

Interesting Jared, can you share some code?