Você está na página 1de 22

Classe genrica para formulrios Parte 01

10 de novembro de 2010 por Paulo Freitas Nobrega Hoje iniciaremos uma srie de artigos que abordam a criao de uma classe php totalmente orientada a objeto para gerao de formulrios. Porm, antes vamos observar brevemente as caractersticas do form, seus atributos e elementos adicionais. Os formulrios HTML so estruturas que permitem a usurios submeterem dados a uma pgina. Esses dados podem ser tratados e/ou armazenados dependendo da aplicao. Possuem uma tag de abertura e outra de fechamento, inserindo os elementos adicionais entre essas duas.
Estrutura: <form (atributos/valores)> (elementos) </form>

Atributos:

accept accept_charset action method enctype

Elementos Adicionais: - input - <input (atributos/valores) /> - option - <option (atributos/valores)> (nome) </option> - select - <select (atributos/valores)> (elemento option) ou (elemento optgroup) </select> - textarea - <textarea (atributos/valores)> (texto) </textarea> - button - <button (atributos/valores)> (nome) </button> - label - <label (atributos/valores)> (rtulo) </label> - fieldset - <fieldset (atributos/valores)> (elemento legend [opcional] ) (elementos) </fieldset> - optgroup - <optgroup (atributos/valores)> (elemento option) </optgroup>

Com base nessas informaes, iniciaremos a construo de nossa classe genrica. Criao da classe commons (comum), attribute (atributo) e element (elemento) O primeiro passo ser a criao das classes genricas, ou seja, as classes que sero utilizadas como extenses para as demais classes. A classe commons ser responsvel pelos mtodos __set() e __get(). A classe attribute ser a instncia de nossos atributos e, por fim, a classe element manipular essas instncias de attribute. Class commons Definiremos a classe commons como abstrata (abstract), pois ela no deve ser instanciada, servir apenas de apoio para as demais. Adicionamos ento dois mtodos

de interceptao (intercepes conceito introduzido no PHP5), o mtodo __set() e __get(). O mtodo __set() interceptar a atribuio de valores a propriedades do objeto. Assim, sempre que for atribudo um valor a uma propriedade do objeto, automaticamente essa atribuio passar pelo mtodo __set(). O mtodo __get() interceptar requisies de propriedades do objeto. Assim, sempre que for requisitada uma propriedade, automaticamente essa requisio passar pelo mtodo __get().
abstract class commons { function __set( $property,$val ) { $this->$property = $val; } function __get( $property ) { return $this->$property; } }

Class attribute A classe attribute ser uma extenso da classe commons, herdando os mtodos __set() e __get(). Definimos tambm a mesma como final. Adicionamos duas variveis, attribute e value, responsveis por guardar o nome do atributo e seu valor. Ento inclumos o mtodo construtor __construct() que atribuir o valor de attribute e value na criao do objeto, caso seja passado algum valor.
final class attribute extends commons { protected $attribute; protected $value; function __construct( $attribute,$value ) { $this->attribute = $attribute; $this->value = $value; } }

Class element A classe element ser uma extenso da classe commons e abstrata (abstract). A funo desta classe ser manipular os objetos attribute, para isso adicionaremos trs mtodos: addAttribute, hasAttributes e getAttributes. Como o prprio nome j descreve, o mtodo addAttribute adicionar na array attributes uma instncia do objeto attribute. A palavra attribute antes de $attribute descreve que a varivel recebida dever ser um objeto attribute. hasAttributes tem a finalidade de verificar se a array attributes possui filhos, retornando um booleano. Por fim, o mtodo getAttributes percorre os atributos contidos na array attribute e os transformam em uma string plana para serem adicionados mais tarde aos elementos.

Definimos tambm o mtodo draw como abstrato (abstract), obrigando as subclasses que herdarem element a implementar draw().
abstract class element extends commons { protected $attributes; final public function addAttribute( attribute $attribute ) { $this->attributes[] = $attribute; } final public function hasAttributes() { return count( $this->attributes ) > 0; } final public function getAttributes() { $elementAttributes = ''; foreach( $this->attributes as $attribute ) { $elementAttributes .= "{$attribute->attribute}=\"{$attribute>value}\" "; } return $elementAttributes; } abstract function draw(); }

No artigo anterior, iniciamos uma srie de artigos, na qual vamos ver a criao de uma classe php totalmente orientada a objeto para gerao de formulrios. J criamos as classes commons, attribute e element, e vamos continuar o processo hoje. Class input Para criar as classes que estendero elementos, devemos observar a estrutura do elemento a ser criado, nesse caso, o input. Estrutura:
<input (atributos/valores) />

Observe que o elemento input bastante simples, possuindo apenas as tags de abertura/fechamento e seus respectivos atributos/valores. Para retornar o elemento com a estrutura acima, vamos utilizar dos mtodos hasAttributre e getAttribute da nossa classe pai element. Segue o cdigo da classe input:
class input extends element { public function draw() { if( parent::hasAttributes() ) { $input = '<input '; $input .= parent::getAttributes(); $input .= ' />' . PHP_EOL; return $input; }

} }

Class textarea Repetiremos o raciocnio aplicado na classe input. Estrutura:


<textarea (atributos/valores)> (texto) </textarea>

O cdigo da classe bem parecido com a classe input, a mudana fica na incluso do construtor __construct(), que agrega varivel value o valor passado no ato da criao do objeto. Segue o cdigo:
class textarea extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $textarea = '<textarea '; if( parent::hasAttributes() ) { $textarea .= parent::getAttributes(); } $textarea .= '>'; if( !empty( $this->value ) ) { $textarea .= $this->value; } $textarea .= '</textarea>' . PHP_EOL; return $textarea; } }

Class Label A classe label segue exatamente a estrutura da classe textarea:


class label extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $label = '<label '; if( parent::hasAttributes() ) { $label .= parent::getAttributes(); } $label .= '>'; if( !empty( $this->value ) ) { $label .= $this->value; } $label .= '</label>' . PHP_EOL; return $label; } }

Class Form A classe form obedece ao mesmo processo de agregao da classe element, tornando um objeto externo parte de si mesmo pela utilizao de seus mtodos. Ou seja, incluiremos ao objeto form instncias dos elementos adicionais. Essas instncias sero armazenadas na array elements e, para serem manipuladas dentro do objeto, utilizaremos dois mtodos, addElement e hasElement. Eles exercem o mesmo trabalho feito na classe element pelos mtodos addAttribute e hasAttribute, adicionar e verificar instncias. Por fim, o mtodo draw() desenha o formulrio.
class form extends element { protected $elements; final public function hasElements() { return count( $this->elements) > 0; } final public function addElement( element $element ) { $this->elements[] = $element; } function draw() { if( $this->hasElements() ) { $form = '<form>' . PHP_EOL; foreach( $this->elements as $element ) { $form .= $element->draw(); } $form .= '</form>'; print $form; } } }

Exemplo da utilizao Vamos realizar um teste para entender o processo obtido. Criaremos dois objetos label, um input e um textarea e os agregaremos ao objeto form. Depois, desenhamos o formulrio executando o mtodo draw().
$labelInput = new label( 'Label Input' ); $labelInput->addAttribute( new attribute( 'for','input' ) ); $labelTextarea = new label( 'Label Textarea' ); $labelTextarea->addAttribute( new attribute( 'for','textarea' ) ); $input = new input; $input->addAttribute( new attribute( 'type','text' ) ); $input->addAttribute( new attribute( 'name','input' ) ); $input->addAttribute( new attribute( 'id','input' ) ); $textarea = new textarea; $textarea->value = 'O texto da textarea caso possua!'; $textarea->addAttribute( new attribute( 'name','textarea' ) ); $textarea->addAttribute( new attribute( 'id','textarea' ) ); $form = new form; $form->addElement( $labelInput ); $form->addElement( $input );

$form->addElement( $labelTextarea ); $form->addElement( $textarea ); $form->draw();

Veja o resultado no cdigo-fonte:


<form> <label for="input">Label Input</label> <input type="text" name="input" id="input" /> <label for="textarea">Label Textarea</label> <textarea name="textarea" id="textarea">O texto da textarea caso possua!</textarea> </form>

Neste ltimo artigo sobre a construo de classes para gerao de formulrios atravs de cdigo orientado ao objeto, iremos abordar as classes dos elementos option, optgroup, select e fieldset. Vamos realizar tambm algumas melhorias em nosso cdigo e adicionar a classe abstrata elementComposite (elemento composto). Confira os artigos anteriores e acompanhe o contedo desta terceira e ltima parte:

Parte 01 Parte 02

Melhorias no cdigo Antes de continuarmos, vamos fazer algumas pequenas melhorias em nosso cdigo. Primeiro no mtodo element. Vamos retirar a funo trim() e alterar a posio do espao em branco, da direita para esquerda, na seguinte linha:
De: $elementAttributes .= "{$attribute->attribute}=\"{$attribute->value}\" "; Para: $elementAttributes .= " {$attribute->attribute}=\"{$attribute>value}\"";

Nos mtodos input, textarea e label, vamos retirar o espao a frente da abertura da tag. Pronto! Segue o cdigo com as alteraes.
abstract class commons { function __set( $property,$val ) { $this->$property = $val; } function __get( $property ) { return $this->$property; } } final class attribute extends commons {

protected $attribute; protected $value; function __construct( $attribute,$value ) { $this->attribute = $attribute; $this->value = $value; } } abstract class element extends commons { protected $attributes; final public function addAttribute( attribute $attribute ) { $this->attributes[] = $attribute; } final public function hasAttributes() { return count( $this->attributes ) > 0; } final public function getAttributes() { $elementAttributes = ''; foreach( $this->attributes as $attribute ) { $elementAttributes .= " {$attribute->attribute}=\"{$attribute>value}\""; } return $elementAttributes; } abstract function draw(); } class input extends element { public function draw() { if( parent::hasAttributes() ) { $input = '<input '; $input .= parent::getAttributes(); $input .= ' />' . PHP_EOL; return $input; } } } class textarea extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $textarea = '<textarea '; if( parent::hasAttributes() ) { $textarea .= parent::getAttributes(); } $textarea .= '>'; if( !empty( $this->value ) ) { $textarea .= $this->value; } $textarea .= '</textarea>' . PHP_EOL;

return $textarea; } } class label extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $label = '<label '; if( parent::hasAttributes() ) { $label .= parent::getAttributes(); } $label .= '>'; if( !empty( $this->value ) ) { $label .= $this->value; } $label .= '</label>' . PHP_EOL; return $label; } }

Note que o mtodo form no est incluso, isso porque no ltimo artigo criamos o mesmo apenas para realizar os testes das classes. Neste artigo, reescreveremos esse mtodo com vrias alteraes. Class elementComposite Como explicado no final do artigo passado, alguns elementos possuem uma estrutura que agrega elementos adicionais, como o caso de form, fieldset, optgroup e select. Todos esses elementos devero agregar uma ou mais instncias de outros objetos. Para isso, devemos criar uma classe abstrata para auxiliar esses elementos nessa tarefa. A classe elementComposite bem parecida com a element, mas em vez de agregar instncias de attribute, agregar instncias de qualquer objeto que seja herdeiro de element. A lgica a mesma: addElement, hasElements e getElements tm as funcionalidades de adicionar, verificar existncia e resgatar instncias. Abaixo o cdigo da classe:
abstract class elementComposite extends element { protected $elements; final public function hasElements() { return count( $this->elements ) > 0; } final public function addElement( element $element ) { $this->elements[] = $element; } final public function getElements() { $out = ''; foreach( $this->elements as $element ) { $out .= $element->draw(); }

return $out; } }

Class form Agora com a classe elementComposite criada fica fcil reescrever a classe form. Veja o resultado:
class form extends elementComposite { function draw() { if( parent::hasElements() ) { $form = '<form '; $form .= parent::getAttributes(); $form .= '>' . PHP_EOL; $form .= parent::getElements(); $form .= '</form>'; return $form; } } }

Class select e optgroup A estrutura aplicada na classe form se repete nas classes select e optgroup:
class optgroup extends elementComposite { public function draw() { if( parent::hasElements() ) { $optgroup = '<optgroup '; if( parent::hasAttributes() ) { $optgroup .= parent::getAttributes(); } $optgroup .= '>' . PHP_EOL; $optgroup .= parent::getElements(); $optgroup .= '</optgroup>' . PHP_EOL; return $optgroup; } } } class select extends elementComposite { public function draw() { if( parent::hasElements() ) { $select = '<select '; if( parent::hasAttributes() ) { $select .= parent::getAttributes(); } $select .= '>' . PHP_EOL; $select .= parent::getElements(); $select .= '</select>' . PHP_EOL; return $select; } } }

Class fieldset

Vamos acrescentar classe fieldset dois mtodos auxiliares alm do mtodo draw() aplicado nas demais, construtor __construct() e setLegend. Ambos sero responsveis por adicionar uma instncia do objeto legend na varivel legend da classe:
class fieldset extends elementComposite { protected $legend; function __construct( $legend ) { if( isset( $legend ) and !empty( $legend ) ) { $this->setLegend( $legend ); } } final public function setLegend( legend $legend ) { $this->legend = $legend; } public function draw() { if( parent::hasElements() ) { $fieldset = '<fieldset '; $fieldset .= parent::getAttributes(); $fieldset .= '>' . PHP_EOL; if( is_object( $this->legend ) ) { $fieldset .= $this->legend>draw(); } $fieldset .= parent::getElements(); $fieldset .= '</fieldset>' . PHP_EOL; return $fieldset; } } }

Class option e legend Para finalizar, criaremos a classe option e legend, ambas estendidas de element. O padro o mesmo seguido nas classes anteriores:
class option extends element { protected $label; function __construct( $label ) { $this->label = $label; } public function draw() { if( !empty( $this->label ) ) { $option = '<option '; if( parent::hasAttributes() ) { $option .= parent::getAttributes(); } $option .= '>'; $option .= $this->label; $option .= '</option>' . PHP_EOL; return $option; } } } class legend extends element {

protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { if( !empty( $this->value ) ) { $legend = '<legend '; if( parent::hasAttributes() ) { $legend .= parent::getAttributes(); } $legend .= '>'; $legend .= $this->value; $legend .= '</legend>' . PHP_EOL; return $legend; } } }

Segue o cdigo completo:


abstract class commons { function __set( $property,$val ) { $this->$property = $val; } function __get( $property ) { return $this->$property; } } final class attribute extends commons { protected $attribute; protected $value; function __construct( $attribute,$value ) { $this->attribute = $attribute; $this->value = $value; } } abstract class element extends commons { protected $attributes; final public function addAttribute( attribute $attribute ) { $this->attributes[] = $attribute; } final public function hasAttributes() { return count( $this->attributes ) > 0; } final public function getAttributes() { $elementAttributes = ''; foreach( $this->attributes as $attribute ) { $elementAttributes .= " {$attribute->attribute}=\"{$attribute>value}\""; } return $elementAttributes; }

abstract function draw(); } abstract class elementComposite extends element { protected $elements; final public function hasElements() { return count( $this->elements ) > 0; } final public function addElement( element $element ) { $this->elements[] = $element; } final public function getElements() { $out = ''; foreach( $this->elements as $element ) { $out .= $element->draw(); } return $out; } } class input extends element { public function draw() { if( parent::hasAttributes() ) { $input = '<input '; $input .= parent::getAttributes(); $input .= ' />' . PHP_EOL; return $input; } } } class textarea extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $textarea = '<textarea '; if( parent::hasAttributes() ) { $textarea .= parent::getAttributes(); } $textarea .= '>'; if( !empty( $this->value ) ) { $textarea .= $this->value; } $textarea .= '</textarea>' . PHP_EOL; return $textarea; } } class option extends element { protected $label; function __construct( $label ) {

$this->label = $label; } public function draw() { if( !empty( $this->label ) ) { $option = '<option '; if( parent::hasAttributes() ) { $option .= parent::getAttributes(); } $option .= '>'; $option .= $this->label; $option .= '</option>' . PHP_EOL; return $option; } } } class label extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $label = '<label '; if( parent::hasAttributes() ) { $label .= parent::getAttributes(); } $label .= '>'; if( !empty( $this->value ) ) { $label .= $this->value; } $label .= '</label>' . PHP_EOL; return $label; } } class legend extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { if( !empty( $this->value ) ) { $legend = '<legend '; if( parent::hasAttributes() ) { $legend .= parent::getAttributes(); } $legend .= '>'; $legend .= $this->value; $legend .= '</legend>' . PHP_EOL; return $legend; } } } class optgroup extends elementComposite { public function draw() { if( parent::hasElements() ) { $optgroup = '<optgroup '; if( parent::hasAttributes() ) { $optgroup .= parent::getAttributes(); }

$optgroup .= '>' . PHP_EOL; $optgroup .= parent::getElements(); $optgroup .= '</optgroup>' . PHP_EOL; return $optgroup; } } } class select extends elementComposite { public function draw() { if( parent::hasElements() ) { $select = '<select '; if( parent::hasAttributes() ) { $select .= parent::getAttributes(); } $select .= '>' . PHP_EOL; $select .= parent::getElements(); $select .= '</select>' . PHP_EOL; return $select; } } } class fieldset extends elementComposite { protected $legend; function __construct( $legend ) { if( isset( $legend ) and !empty( $legend ) ) { $this->setLegend( $legend ); } } final public function setLegend( legend $legend ) { $this->legend = $legend; } public function draw() { if( parent::hasElements() ) { $fieldset = '<fieldset '; $fieldset .= parent::getAttributes(); $fieldset .= '>' . PHP_EOL; if( is_object( $this->legend ) ) { $fieldset .= $this->legend>draw(); } $fieldset .= parent::getElements(); $fieldset .= '</fieldset>' . PHP_EOL; return $fieldset; } } } class form extends elementComposite { function draw() { if( parent::hasElements() ) { $form = '<form '; $form .= parent::getAttributes(); $form .= '>' . PHP_EOL; $form .= parent::getElements(); $form .= '</form>'; return $form; } } }

Demonstrao: Para finalizar o artigo, vamos simular alguns casos para observar a utilizao das classes criadas: 01. Formulrio simples: Carlos ser nosso personagem, ele quer exibir um formulrio simples em seu site. Esse formulrio deve conter: Campo input text e label do mesmo Campo textarea e label do mesmo Boto de submisso Segue o cdigo:
$labelInput = new label( 'label input' ); $labelInput->addAttribute( new attribute( 'for','meuinput' ) ); $input = new input; $input->addAttribute( new attribute( 'type','text' ) ); $input->addAttribute( new attribute( 'name','meuinput' ) ); $input->addAttribute( new attribute( 'id','meuinput' ) ); $labelTextarea = new label( 'label textarea' ); $labelTextarea->addAttribute( new attribute( 'for','minhatextarea' ) ); $textarea = new textarea; $textarea->addAttribute( new attribute( 'name','minhatextarea' ) ); $textarea->addAttribute( new attribute( 'id','minhatextarea' ) ); $submit = new input; $submit->addAttribute( new attribute( 'type','submit' ) ); $submit->addAttribute( new attribute( 'value','enviar' ) ); $form = new form; $form->addElement( $labelInput ); $form->addElement( $input ); $form->addElement( $labelTextarea ); $form->addElement( $textarea ); $form->addElement( $submit ); print $form->draw();

02. Select dinmico Agora Carlos deseja popular um select com dados vindos do banco de dados. Segue o cdigo:
#array simulando retorno de dados do db $arrQuery = array( array( 'arroz',1 ), array( 'feijao',2 ), array( 'bife',3 ) ); $select = new select; $select->addAttribute( new attribute( 'name','myselect' ) );

foreach( $arrQuery as $val ) { $option = new option( $val[0] ); $option->addAttribute( new attribute( 'value',$val[1] ) ); $select->addElement( $option ); } $form = new form; $form->addElement( $select ); print $form->draw();

03. Utilizando todas classes Carlos dessa vez deseja utilizar todas as classes criadas. Segue o cdigo:
$labelInput = new label( 'label input' ); $labelInput->addAttribute( new attribute( 'for','meuinput' ) ); $input = new input; $input->addAttribute( new attribute( 'type','text' ) ); $input->addAttribute( new attribute( 'name','meuinput' ) ); $input->addAttribute( new attribute( 'id','meuinput' ) ); $labelTextarea = new label( 'label textarea' ); $labelTextarea->addAttribute( new attribute( 'for','minhatextarea' ) ); $textarea = new textarea; $textarea->addAttribute( new attribute( 'name','minhatextarea' ) ); $textarea->addAttribute( new attribute( 'id','minhatextarea' ) ); $labelSelect = new label( 'label select' ); $labelSelect->addAttribute( new attribute( 'for','meuselect' ) ); $select = new select; $select->addAttribute( new attribute( 'name','meuselect' ) ); $select->addAttribute( new attribute( 'id','meuselect' ) ); $option1 = new option( 'option1' ); $option2 = new option( 'option2' ); $option3 = new option( 'option3' ); $option1->addAttribute( $option2->addAttribute( $option2->addAttribute( $option3->addAttribute( new new new new attribute( attribute( attribute( attribute( 'value',1 ) ); 'value',2 ) ); 'selected','selected' ) ); 'value',3 ) );

$optgroup = new optgroup; $optgroup->addAttribute( new attribute( 'label','option 1 e 2' ) ); $optgroup->addElement( $option1 ); $optgroup->addElement( $option2 ); $select->addElement( $optgroup ); $select->addElement( $option3 ); $submit = new input; $submit->addAttribute( new attribute( 'type','submit' ) ); $submit->addAttribute( new attribute( 'value','enviar' ) ); $legend = new legend( 'meu formulrio' ); $fieldset = new fieldset;

$fieldset->setLegend( $legend ); $fieldset->addElement( $labelInput ); $fieldset->addElement( $input ); $fieldset->addElement( $labelTextarea ); $fieldset->addElement( $textarea ); $fieldset->addElement( $labelSelect ); $fieldset->addElement( $select ); $fieldset->addElement( $submit ); $form = new form; $form->addAttribute( new attribute( 'name','meuform' ) ); $form->addElement( $fieldset ); print $form->draw();

Chegamos ao fim desta srie. Espero ter colaborado e/ou auxiliado vocs! Vou deixar o cdigo da classe implementada para suportar multiplas adies de atributos e de elementos:
abstract class commons { function __set( $property,$val ) { $this->$property = $val; } function __get( $property ) { return $this->$property; } } final class attribute extends commons { protected $attribute; protected $value; function __construct( $attribute,$value ) { $this->attribute = $attribute; $this->value = $value; } } abstract class element extends commons { protected $attributes; final public function addAttribute( $attribute ) { if( is_object( $attribute ) and $attribute instanceof attribute ) { $this->attributes[] = $attribute; } elseif( is_array( $attribute ) ) { foreach( $attribute as $obj ) { if( is_object( $obj ) and $obj instanceof attribute ) { $this->attributes[] = $obj; } } } } final public function hasAttributes() { return count( $this->attributes ) > 0; } final public function getAttributes() {

if( $this->hasAttributes() ) { $elementAttributes = ''; foreach( $this->attributes as $attribute ) { $elementAttributes .= " {$attribute->attribute}=\"{$attribute>value}\""; } return $elementAttributes; } } abstract function draw(); } abstract class elementComposite extends element { protected $elements; final public function hasElements() { return count( $this->elements ) > 0; } final public function addElement( $element ) { if( is_object( $element ) and is_subclass_of( $element,'element' ) ) { $this->elements[] = $element; } elseif( is_array( $element ) ) { foreach( $element as $obj ) { if( is_object( $obj ) and is_subclass_of( $obj,'element' ) ) { $this->elements[] = $obj; } } } } final public function getElements() { if( $this->hasElements() ) { $out = ''; foreach( $this->elements as $element ) { $out .= $element->draw(); } return $out; } } } class input extends element { public function draw() { if( parent::hasAttributes() ) { $input = '<input '; $input .= parent::getAttributes(); $input .= ' />' . PHP_EOL; return $input; } } } class textarea extends element {

protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $textarea = '<textarea '; if( parent::hasAttributes() ) { $textarea .= parent::getAttributes(); } $textarea .= '>'; if( !empty( $this->value ) ) { $textarea .= $this->value; } $textarea .= '</textarea>' . PHP_EOL; return $textarea; } } class option extends element { protected $label; function __construct( $label ) { $this->label = $label; } public function draw() { if( !empty( $this->label ) ) { $option = '<option '; if( parent::hasAttributes() ) { $option .= parent::getAttributes(); } $option .= '>'; $option .= $this->label; $option .= '</option>' . PHP_EOL; return $option; } } } class label extends element { protected $value; function __construct( $value ) { $this->value = $value; } public function draw() { $label = '<label '; if( parent::hasAttributes() ) { $label .= parent::getAttributes(); } $label .= '>'; if( !empty( $this->value ) ) { $label .= $this->value; } $label .= '</label>' . PHP_EOL; return $label; } } class legend extends element { protected $value;

function __construct( $value ) { $this->value = $value; } public function draw() { if( !empty( $this->value ) ) { $legend = '<legend '; if( parent::hasAttributes() ) { $legend .= parent::getAttributes(); } $legend .= '>'; $legend .= $this->value; $legend .= '</legend>' . PHP_EOL; return $legend; } } } class optgroup extends elementComposite { public function draw() { if( parent::hasElements() ) { $optgroup = '<optgroup '; if( parent::hasAttributes() ) { $optgroup .= parent::getAttributes(); } $optgroup .= '>' . PHP_EOL; $optgroup .= parent::getElements(); $optgroup .= '</optgroup>' . PHP_EOL; return $optgroup; } } } class select extends elementComposite { public function draw() { if( parent::hasElements() ) { $select = '<select '; if( parent::hasAttributes() ) { $select .= parent::getAttributes(); } $select .= '>' . PHP_EOL; $select .= parent::getElements(); $select .= '</select>' . PHP_EOL; return $select; } } } class fieldset extends elementComposite { protected $legend; function __construct( $legend ) { if( isset( $legend ) and !empty( $legend ) ) { $this->setLegend( $legend ); } } final public function setLegend( legend $legend ) { $this->legend = $legend; } public function draw() { if( parent::hasElements() ) { $fieldset = '<fieldset ';

$fieldset .= parent::getAttributes(); $fieldset .= '>' . PHP_EOL; if( is_object( $this->legend ) ) { $fieldset .= $this->legend>draw(); } $fieldset .= parent::getElements(); $fieldset .= '</fieldset>' . PHP_EOL; return $fieldset; } } } class form extends elementComposite { function draw() { if( parent::hasElements() ) { $form = '<form '; $form .= parent::getAttributes(); $form .= '>' . PHP_EOL; $form .= parent::getElements(); $form .= '</form>'; return $form; } } }

Utilizao:
$labelInput = new label( 'label input' ); $labelInput->addAttribute( new attribute( 'for','input' ) ); $labelSelect = new label( 'label select' ); $labelSelect->addAttribute( new attribute( 'for','select' ) ); $labelTextarea = new label( 'label textarea' ); $labelTextarea->addAttribute( new attribute( 'for','textarea' ) ); $legend = new legend( 'meu fieldset' ); $input = new input; $input->addAttribute( array( new attribute( 'type','text' ), new attribute( 'name','input' ), new attribute( 'id','input' ) ) ); $select = new select; $select->addAttribute( new attribute( 'name','select' ) ); $select->addAttribute( new attribute( 'id','select' ) ); $arroz = new option( 'arroz' ); $arroz->addAttribute( new attribute( 'value',1 ) ); $feijao = new option( 'feijao' ); $feijao->addAttribute( new attribute( 'value',2 ) ); $bife = new option; $bife->label = 'bife'; $bife->addAttribute( array ( new attribute( 'value',3 ), new attribute( 'selected','selected' ) ) ); $graos = new optgroup; $graos->addAttribute( new attribute( 'label','graos' ) ); $graos->addElement( array( $arroz, $feijao ) ); $select->addElement( array( $graos, $bife ) );

$textarea = new textarea; $textarea->addAttribute( array( new attribute( 'name','textarea' ), new attribute( 'id','textarea' ) ) ); $submit = new input; $submit->addAttribute( array( new attribute( 'type','submit' ), new attribute( 'value','enviar' ) ) ); $fieldset = new fieldset; $fieldset->setLegend( $legend ); $fieldset->addElement( array( $labelInput,$input,$labelSelect,$select,$labelTextarea,$textarea,$subm it ) ); $form = new form; $form->addAttribute( array( new attribute( 'name','form' ), new attribute( 'method','post' ) ) ); $form->addElement( $fieldset ); print $form->draw();

Você também pode gostar