Sometimes this is necessary, especially when are working with MVC design pattern. This gives Controller class access to View elements for manipulating before that HTML tag/element is rendered.
Here are list of the benefits of wrapping HTML tags in PHP class object:
- Various parts of application can access View elements
- Work with HTML code as you would for php objects.
- Customize and reuse HTML tags
- Easier and useful to work with nested and complex tags such as lists (<ul>,<ol>, <dl>), forms (<form>)
- Create compound HTML elements, such as a input control with a label. This requires two different tags, but using php object we can encapsulate them into one object.
How to use HTML element object in php
Lets first look at how we will use the HTML element objects. Then we will explore how to write the class file. We will name our class 'HtmlElement'.In the real world, you may not want use this technique to render all of your HTML tags. However lets say you want plugins or other parts of application to be able to modify and customize the $content element. In such case you can simply pass the $content variable among various parts of your application. When they are all done, you can then simply render the $content variable.<?php
// create the paragraph tag
$p = new HtmlElement('p');
$p->align = "center"; // adding html tag attribute
$p->append('This is a paragraph.'); // add the inner text of the tag
// create a div section
$content = new HtmlElement('div');
$content->style = 'padding:4px';
$content->id = 'main_section';
$content->append($p); // add the p tag previously created.
// finally outputting
print $content;
// this will output
// <div style="padding:4px;" id="main_section"><p align="center">This is a paragraph</p></div>
?>
Things will start to get more interesting when we extend the HtmlElement and start building customized controls and views. We will look into that in the next part of this series. Now lets get started with the code.
Coding HtmlElement
HtmlElement will be our base class for rendering all HTML tags. All compound HTML objects will inherit from this. There are three part in the implementation of the HtmlElement- HTML tag name
- attributes for that HTML tag
- finally rendering
Let's get started.
class HtmlElement
{
protected
$_attributes = array(), // holds html tag attributes
$_tag = null, // name of the tag
$_content = ''; // contents of the tag
/**
* constructing the tag element
* we enforce to specify the tag name when creating to make things logically accurate.
*/
public function __construct($tag, $content = '', $attributes = null)
{
$this->_tag = $tag;
$this->_content = $content;
$this->_attributes = $attributes;
}
/**
* we add given string after current content
*/
public function append($str)
{
$this->_content .= $str;
}
/**
* will add given string before the content
*/
public function prepend($str)
{
$this->_content = $str . $this->_content;
}
// ... rest of the code here
}
Construction is self explanatory. First argument is the tag name which is required. Second and third arguments are optional. They are for content of the tag and it's attributes respectively. We also added two additional methods to add to the content (inner html/text of the tag). As name implies, append adds string end of the current text and prepend adds in the begining.
So lets started with attributes. Attributes are implemented using php's magic __get and __set methods and fairly easy to do so.
class HtmlElement
{
// ... previous codes
/**
* sets an attribute
*/
public function __set($key, $value)
{
$this->_attributes[$key] = $value;
}
/**
* get attribute value
*/
public function __get($key)
{
if(isset($this->_attributes[$key])) return $this->_attributes[$key];
return null;
}
/**
* returns all attributes as key=value string
*/
public function attributeString()
{
if(empty($this->_attributes)) return;
$str = '';
foreach($this->_attributes as $key => $value) {
$str .= "{$key}=\"{$value}\" ";
}
return trim($str);
}
... // rest of the code
}
So lets started with attributes. Attributes are implemented using php's magic __get and __set methods and fairly easy to do so.
class HtmlElement
{
// ... previous codes
/**
* sets an attribute
*/
public function __set($key, $value)
{
$this->_attributes[$key] = $value;
}
/**
* get attribute value
*/
public function __get($key)
{
if(isset($this->_attributes[$key])) return $this->_attributes[$key];
return null;
}
/**
* returns all attributes as key=value string
*/
public function attributeString()
{
if(empty($this->_attributes)) return;
$str = '';
foreach($this->_attributes as $key => $value) {
$str .= "{$key}=\"{$value}\" ";
}
return trim($str);
}
... // rest of the code
}
As you can see, in addition to magic function, we created a special method called attributeString(). This method will return all attributes in key=value text format which is used for HTML tags. When we render the tag to output HTML, we need this method. So, let's get started with rendering!
Rendering HTML output
class HtmlElement
{
// ... previous codes
/**
* render the html tag and returns html string
*/
public function render()
{
$output = $this->_renderStartTag();
$output .= $this->_renderInnerHtml();
$output .= $this->_renderEndTag();
return $output;
}
protected function _renderStartTag()
{
$attributes = $this->attributeString();
if(attributes) {
return "<{$this->_tag} {$attributes}>";
} else {
return "<{$this->_tag}>";
}
}
protected function _renderInnerHtml()
{
return $this->_content;
}
protected function _renderEndTag()
{
return "</{$this->_tag}>";
}
public function __toString()
{
return $this->render();
}
}
Ok, lets see what's going on here. We have divided rendering into four different methods. First one is render(), which is public, and the rest three are protected methods responsibles for rendering start of the tag, tag content and end of the tag. You can think of these protected methods as internal events. When subclassing, these events comes very handly. This will be discussed in next part of this article.
Finally we implemented another php magic function called __toString(). This method simply calls render method. By implementing this method, we are able to output and treat this object as a string.
Finally we implemented another php magic function called __toString(). This method simply calls render method. By implementing this method, we are able to output and treat this object as a string.
There are lots of room for improvement, but to keep things simple and to focus on the concept, this implementation will be sufficient. Remember this HtmlElement class will be base class for all further UI elements.
Comment(s):
Great! Nice, clear and easy to understand. Keep up the good work. I look forward to the next installment.
by vk3ama | on Friday 11th December 2009Post a new comment
Use the form below to enter a new comment for this blog.