XHTML widgets with object-oriented PHP

Producing markup is one of the main tasks that PHP must perform. However, this is sometimes a tedious task that forces us to embed our PHP code in the markup itself, which is not a good programming practice. We can ease the difficulty of this task with an object-oriented approach. Basically, widgets are small objects that can be used in various contexts. In our case, we need to create small chunks of code for XHTML elements. Here's an example:

class XHTML_Widget
  protected $_type;

  public function __construct($type)
    $this->_type = $type;

  public function drawWidget($attributes = '', $content = '')
   return '<' . $this->_type .  ' ' . $attributes . '>' . $content . '</' . $this->_type . '>';

Then the class can be used as follows:


$link = new XHTML_Widget('a');
echo $link->drawWidget('href="#"', 'Click me');

Note, however, that this class could be declared as abstract (and also its methods), for a better use of the encapsulation process.

Leave a Reply

Note: Only a member of this blog may post a comment.