I always hated the way I sometimes had to mix strings of HTML with code when outputting something like a navigation list in PHP. In particular I don’t like the way you’re mixing variables with bits of code in a very linear fashion, mixing if statements in between tags etc.
For example:
[code=php]
$html = ‘<ul class=”channel clearfix”>’;
$html .= ‘<li class=”first’;
if ($this->isChannel(1)) $html .= ‘ selected’;
$html .= ‘”><a href=”‘ . $this->getLinkByChannel(1) . ‘”>Channel 1</a></li>’;
$html .= ‘<li’;
if ($this->isChannel(2)) $html .= ‘ class=”selected”‘;
$html .= ‘><a href=”‘ . $this->getLinkByChannel(2) . ‘”>Channel 2</a></li>’;
$html .= ‘</ul>’;
return $html;
I’ve started using a class which lets you create tags as objects and add properties/attributes, content, etc. at any stage, which removes the hassle of dealing with strings of HTML mixed with code and makes the code more flexible, easier to manage, and in my opinion, sometimes easier to read.
I was wondering what other’s thoughts were on this – which is the best way in your opinion? I’ve done some benchmarking and obviously the first way (writing out straight HTML) is faster. But for some things it can be much easier to write and update code if you’re using the object-oriented approach.
The examples used here are pretty simple and may seem like overkill but I’ve found it useful for some more complex HTML where what’s generated depends on many factors.
Here’s an example of the object-based code:
[code=php]
$ul = new HtmlElement(‘ul’, NULL, NULL, ‘channel clearfix’);
$li1 = new HtmlElement(‘li’);
($this->isChannel(1)) ? $li1->setClass(‘first selected’) : $li1->setClass(‘first’);
$a1 = new HtmlElement(‘a’, ‘Channel 1’);
$a1->addAttribute(‘href’, $this->getLinkByChannel(1));
$li1->addChild($a1);
$ul->addChild($li1);
$li2 = new HtmlElement(‘li’);
if ($this->isChannel(2)) $li2->setClass(‘selected’);
$a2 = new HtmlElement(‘a’, ‘Channel 2’);
$a2->addAttribute(‘href’, $this->getLinkByChannel(2));
$li2->addChild($a2);
$ul->addChild($li2);
return $ul->getOutput();
And here’s what the final HTML looks like:
[code=html]
<ul class=”channel clearfix”>
<li class=”first selected”><a href=”?c=1&d=0&t=4″>Channel 1</a></li>
<li><a href=”?c=2&d=0&t=4″>Channel 2</a></li>
</ul>