
Originally Posted by
SilverBulletUK
I was thinking something more along these lines...
Of course there are lots of ways this can be improved, but it should give you a rough idea.
Thank you so much for that code, it sure helps!
I don't see the need to have a class for each form element so I simplified your code a bit. My version has a single Tag class and the constructor is passed the actual tag (input, button, etc.):
PHP Code:
<?php
class Form
{
protected $sAction;
protected $sMethod;
protected $aTags = array();
public function __construct($sAction, $sMethod = 'post')
{
$this->sAction = $sAction;
$this->sMethod = $sMethod;
}
public function addTag(Tag $oTag)
{
$this->aTags[] = $oTag;
}
public function render()
{
foreach ($this->aTags as $oTag)
{
$sTags .= $oTag->render() . "\r\n";
}
return sprintf(
'<form action="%s" method="%s">
%s
</form>',
$this->sAction,
$this->sMethod,
$sTags
);
}
}
class Tag
{
protected $sTag;
protected $sDisplayText;
protected $aAttributes;
public function __construct($sTag, $sDisplayText = '')
{
$this->sTag = $sTag;
$this->sDisplayText = $sDisplayText;
}
public function addAttribute($sName, $mValue)
{
$this->aAttributes[$sName] = $mValue;
}
public function render()
{
if (is_array($this->aAttributes))
{
foreach ($this->aAttributes as $sName => $mValue)
{
$sAttributes .= sprintf('%s="%s" ', $sName, $mValue);
}
}
if ($this->sDisplayText == '')
{
return sprintf(
'<%s %s/>',
$this->sTag,
$sAttributes
);
} else {
return sprintf(
'<%s %s>%s</%s>',
$this->sTag,
$sAttributes,
$this->sDisplayText,
$this->sTag
);
}
}
}
$oForm = new Form('/users/login/');
$oUsernameField = new Tag('input');
$oUsernameField->addAttribute('type', 'text');
$oUsernameField->addAttribute('name', 'username');
$oBr = new Tag('br');
$oPasswordField = new Tag('input');
$oPasswordField->addAttribute('type', 'password');
$oPasswordField->addAttribute('name', 'password');
$oSubmitButton = new Tag('button', 'Click Me!');
$oSubmitButton->addAttribute('type', 'submit');
$oSubmitButton->addAttribute('name', 'submit');
$oSubmitButton->addAttribute('value', 'login');
$oForm->addTag($oUsernameField);
$oForm->addTag($oBr);
$oForm->addTag($oPasswordField);
$oForm->addTag($oBr);
$oForm->addTag($oSubmitButton);
echo $oForm->render();
/*
<form action="/users/login/" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit" name="submit" value="login" >Click Me!</button>
</form>
*/
?>
Would you be kind enough to explain this line of code
PHP Code:
public function addTag(Tag $oTag)
I don't understand the function of the class name parameter it takes.
Bookmarks