HTMLHelper Class
Un ayudante de html permite generar etiquetas html de una manera ordenada, mediante la invocación de funciones o métodos y el envio de los parámetros necesarios.
La clase que verá a continuación es un HTMLHelper, que se vale de la sobrecarga que php5 nos proporciona para simplificar un poco el trabajo.
El código está completamente documentado, si hay algo que no entiende o quiere sugerir una mejora, deje un comentario en el articulo.
<?php
/**
* Ayudante de HTML
*/
class HTMLHelper {
/**
* Contiene un array de elementos sin cuerpo (<tag />)
* @var <array>
*/
private $singles;
public function __construct() {
//Inicializamos el array con los elementos que no tiene cuerpo
$this->singles = array('input', 'hr', 'br');
}
/**
* La gran magia... invoca los creadores de elementos y retorna el html
* @param <string> tag
* @param <array> atributos
* @return <string> el html generado
*/
public function __call($name, $arguments) {
if(!in_array($name, $this->singles)) {
$attributes = $this->attributes($arguments[1]);
$content = $arguments[0];
return $this->container($name, $content, $attributes);
}else {
$attributes = $this->attributes($arguments[0]);
return $this->single($name, $attributes);
}
}
/**
* Convierte un array asociativo en una coleccion de atributos html
* @param <array> $attr
* @return <string>
*/
private function attributes($attr = null) {
$attributes = '';
if(!is_null($attr) && is_array($attr)) {
foreach($attr as $key => $value) {
$attributes .= ' '.$key.'="'.$value.'"';
}
}
return $attributes;
}
/**
* Genera un elemento con cuerpo (<tag></tag>)
* @param <string> tag
* @param <string> cuerpo
* @param <array> atributos
* @return <string> html
*/
private function container($name, $content, $extra = null) {
$html = '<'.$name.$extra.'>'.$content.'</'.$name.'>';
return $html;
}
/**
* Genera un elemento sin cuerpo (<tag />)
* @param <string> tag
* @param <array> atributos
* @return <string> html
*/
private function single($name, $extra = null) {
$html = '<'.$name.$extra.' />';
return $html;
}
}
?>
Modo de uso
<?php
//Modo de uso
$html = new HTMLHelper;
$title = $html->h1('Formulario de contacto');
$fields = $html->input(array('type' => 'text', 'name' => 'nombre'));
$countries = $html->option('Argentina', array('value' => 1));
$countries .= $html->option('España', array('value' => 2));
$countries .= $html->option('Mexico', array('value' => 3));
$fields.= $html->select($countries, array('name' => 'pais'));
$fields.= $html->textarea('Coloque aqui su mensaje...', array('name' => 'mensaje'));
$form = $html->form($fields, array('method' => 'post', 'action' => '/'));
echo $html->div($title.$form), "\n";
?>
Luego de crear una instancia de la clase HTMLHelper nos valemos de sus métodos mágicos para ir generando el html paso a paso.
Como podrá ver, se utilizan variables temporales (caso $title, $fields, $countries, etc) para almacenar temporalmente la salida html y luego volcarla al navegador en la última instrucción.
Html generado
<div><h1>Formulario de contacto</h1><form method="post" action="/"><input type="text" name="nombre" /><select name="pais"><option value="1">Argentina</option><option value="2">España</option><option value="3">Mexico</option></select><textarea name="mensaje">Coloque aqui su mensaje...</textarea></form></div>
En realidad la clase genera XHTML.