I have a PHP class for building HTML tags. Each HTML tag becomes of new instance. I have some utility methods needed within the class for handling certain functional stuff like escaping attributes and for configuring certain options that affect all instances. I'm declaring the utilities and public static
and within the class I'm using self::
to call the utility methods. Do you think it's better to keep all the methods in one class or to create a separate static class for the utilities and have it so the main class extends the static one (so that I can still call the methods with self::
)? What is the best way to handle this type of situation? (in PHP 5.2 and up) The interface for the class is like this:
foo('div')->attr('id', 'example')->html('this is inner text')->get();
foo('img')->attr(array('src' => 'example.png', 'alt' => 'example'))->get();
Example of the underlying code:
public function attr($name, $value = '')
{
if (is_scalar($name))
{
if (empty($name) && !is_int($name)) $this->attrs[] = $value;
else $this->attrs[$name] = $value;
}
else
{
foreach ((array) $name as $k => $v)
{
$this->attr($k, $v);
}
}
return $this;
}
// handler (doesn't get called until it's time to get)
public static function attr_encode($name, $value = '')
{
if (is_scalar($name))
{
if (is_int($name)) return self::attr_encode($value, '');
$name = preg_replace(self::ATTR_NAME_INVALIDS, '', $name);
if ('' === $name) return '';
if (1 === func_num_args() || '' === $value) return $name;
$value = is_null($value) ? 'null' : ( !is_scalar($value) ? (
self::supports('ssv', $name) ? self::ssv_implode($value) : json_encode($value)) : (
is_bool($value) ? (true === $value ? 'true' : 'false') : self::esc_attr($value)));
return $name . "='" . $value . "'"; // Use single quotes for compatibility with JSON.
}
// Non-scalar - treat $name as key/value map:
$array = array();
foreach ((array) $name as $attr_name => $attr_value)
{
self::push($array, true, self::attr_encode($attr_name, $attr_value));
}
return implode(' ', $array);
}