Home » HTML » HTML_Common2 » Manual
The HTML_Common2 package provides methods for HTML attributes handling and setting document-wide options. It is quite helpful as a building block for packages generating HTML and is currently used as such by HTML_QuickForm2 package. Main features: Allows easy setting, removing, merging of HTML attributes, working with CSS classes; Provides means to parse and generate HTML attribute strings; Global document options: charset, linebreak and indentation characters; Methods to handle indentation and HTML comments (useful in subclasses). Note that HTML_Common2 is an abstract class, so you would probably subclass it and use a instance of a child class rather than HTML_Common2 itself. One notable exception is using its static methods to get and set global document options.
Attributes
Attributes – Working with HTML attributes.
Methods for Attributes Handling
HTML_Common2 class is intended as a parent class for classes representing HTML elements and its main purpose is to allow easy attribute handling for instances of these child classes.
Inividual attribute values can be set by HTML_Common2::setAttribute() and read by HTML_Common2::getAttribute() methods. Use HTML_Common2::removeAttribute() to remove an attribute, calling setAttribute() without explicitly giving a new attribute value serves a different purpose:
<?php
// these calls are identical
$html->setAttribute('checked');
$html->setAttribute('checked', 'checked');
?>
You can completely replace attributes of HTML_Common2 instance by using HTML_Common2::setAttributes() method and add/replace several new attributes at once by using HTML_Common2::mergeAttributes(). By default constructor of HTML_Common2 calls mergeAttributes(), so that some default attributes can be provided by a subclass and only overridden if needed. Note that both of the above methods can accept either a string of HTML attributes or an array of these.
Finally, HTML_Common2::getAttributes() method returns the values of all the instance's attributes. Those can be returned either as an associative array or a string. As the package is intended for XHTML-compliant output, attribute names will always be lowercased and quotes will be used around attribute values when outputting the attribute string.
Using array notation
Since release 2.1.0 HTML_Common2 implements ArrayAccess interface, allowing access to attributes using array notation:
Accessing attributes as array keys
<?php
if (!isset($html['id'])) {
// equivalent to $html->setAttribute('id', 'foo');
$html['id'] = 'foo';
}
// equivalent to $html->setAttribute('checked');
$html[] = 'checked';
// equivalent to $html->removeAttribute('checked');
unset($html['checked']);
?>
Working with CSS Classes
HTML_Common2 contains several methods to easily handle
'class' attribute of HTML tags: HTML_Common2::addClass(), HTML_Common2::removeClass() and HTML_Common2::hasClass(). Their behaviour should be easily deducable from their
names:
<?php
$html->setAttribute('class', 'foo bar');
$html->removeClass('foo');
if (!$html->hasClass('foo')) {
$html->addClass('notFoo');
}
echo $html->getAttribute('class');
?>will output
bar notFoo
Usage Example
The following example shows a somewhat minimal subclass of HTML_Common2 and possible ways to change its attributes.
Methods available for attribute handling
<?php
// a non-abstract subclass of HTML_Common2
class HTML_Tag_Foo extends HTML_Common2
{
// some predefined attributes, won't be overwritten
protected $attributes = array('class' => 'pretty');
// basic implementation of magic __toString() method
public function __toString()
{
return '<foo' . $this->getAttributes(true) . ' />';
}
}
$foo = new HTML_Tag_Foo(array('size' => 'small', 'align' => 'top left corner',
'foo' => 'foo value'));
// note how the attributes from this string will be handled
$foo->mergeAttributes("bar LEVEL=0 value='Whatever'");
$foo->removeAttribute('align');
$foo->setAttribute('size', 'smaller');
echo $foo;
?>
The above code will output:
<foo class="pretty" size="smaller" foo="foo value" bar="bar" level="0" value="Whatever" />
Options
Options – Setting document-wide options.
Overview
HTML_Common2 provides static HTML_Common2::setOption() and HTML_Common2::getOption() methods for defining the document-wide configuration. Predefined options in HTML_Common2 are:
'charset'-
Charset parameter to use in htmlspecialchars()
calls, defaults to
'ISO-8859-1'
'indent'-
string used to indent HTML elements, defaults to
"\11"
'linebreak'-
string used to indicate linebreak, defaults to
"\12"
It is suggested that child classes of HTML_Common2 use the above parameters when generating HTML.
Note that setOption() and getOption() allow any option names so packages depending on HTML_Common2 may add their own configuration:
<?php
HTML_Common2::setOption('my_option_name', 'My option value');
// ...
if (HTML_Common2::getOption('my_option_name')) {
// do something
}
?>
getOption() will return NULL for an unknown option name, it will return an array of all options and their values if option name is omitted.
Subclassing HTML_Common2
Subclassing HTML_Common2 – Protected methods, output formatting, "watched" attributes.
Output formatting
HTML_Common2 does not generate any HTML itself, except for a HTML attribute string. However, it provides several methods and configuration parameters that can be used by child classes to format their output.
It is possible to specify indentation level of the current tag via HTML_Common2::setIndentLevel() and HTML comment to output beside tag via HTML_Common2::setComment(). These methods have corresponding getters HTML_Common2::getIndentLevel() and HTML_Common2::getComment().
There is also a protected HTML_Common2::getIndent() method that returns a string to indent the current tag
based on indent level and 'indent' configuration parameter.
Protected Methods
Child classes may take advantage of protected static methods for handling of attributes strings and arrays:
- HTML_Common2::getAttributesString()
- Creates a HTML attribute string from a given attribute array.
- HTML_Common2::parseAttributes()
- Parses a given attribute string into an attribute array, properly handles non-XHTML strings.
- HTML_Common2::prepareAttributes()
-
Creates a proper attribute array from given array or string. Attribute names are
lowercased, integer-based keys are converted to
('value' => 'value'). This is the preferred method to handle incoming attributes.
Monitoring Changes to Specific Attributes
It is sometimes necessary either to prevent changing some attribute of a HTML tag (e.g.
type attribute of <input /> element) or monitor
changes to an attribute to do some additional processing (e.g. on changing element's
id attribute we should also update some references to that attribute).
HTML_Common2 provides means to do this additional processing in the form
of HTML_Common2::$watchedAttributes
property and HTML_Common2::onAttributeChange() method. When a change of an attribute with name
in $watchedAttributes array is attempted,
onAttributeChange() is called instead of performing the attempted change. It
is up to the programmer implementing the method to decide what to do with the attribute.
Usage Example
The following code prevents setting type attribute except via
constructor and to update the value attribute when name
attribute changes. It also shows how to use methods provided by
HTML_Common2 to format the resultant HTML.
Complex subclass of HTML_Common2
<?php
$_REQUEST = array(
'foo' => 'Foo value',
'bar' => 'Bar value'
);
class HTML_Tag_Input extends HTML_Common2
{
protected $watchedAttributes = array('name', 'type');
public function __construct($type, $name, $attributes = null)
{
$this->attributes['type'] = (string)$type;
$this->setName($name);
parent::__construct($attributes);
}
public function setName($name)
{
$this->attributes['name'] = (string)$name;
if (!empty($_REQUEST[$name])) {
$this->attributes['value'] = $_REQUEST[$name];
}
}
protected function onAttributeChange($name, $value)
{
if ('type' == $name) {
throw new Exception("Attribute 'type' is read-only");
} elseif ('name' == $name) {
if (null === $value) {
throw new Exception("Required attribute 'name' cannot be removed");
}
$this->setName($value);
}
}
public function __toString()
{
return ($this->getComment()
? $this->getIndent() . '<!-- ' . $this->getComment() . ' -->' . HTML_Common2::getOption('linebreak')
: '')
. $this->getIndent() . '<input' . $this->getAttributes(true) . ' />';
}
}
$input = new HTML_Tag_Input('text', 'foo');
echo $input . "\n";
try {
$input->setAttribute('type', 'file');
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
$input->setAttribute('name', 'bar')
->setIndentLevel(1)
->setComment('Simplified version of HTML_QuickForm2_Element_Input');
echo $input;
?>
The above code will produce the following output:
<input type="text" name="foo" value="Foo value" />
Attribute 'type' is read-only
<!-- Simplified version of HTML_QuickForm2_Element_Input -->
<input type="text" name="bar" value="Bar value" />