I've been toying with the idea of using the value object pattern to ensure my strings are always escaped when they should be but never twice. The problem I find is that escaping at the last possible moment e.g. view layer of MVC means you can't preprocess anything with HTML formatting and escaping as early as possible means length calculations and the like are out of wack. I don't particularly want to decode HTML entities because I consider this an expensive action that can be avoided so my solution is something where tracking is possible. I'm not really sure what the implications/limitations of this are so comment away.
Outputs:
Code: Select all
<a><b>kCode: Select all
<?php
class Str
{
private $_string = '';
private $_destination;
public function __construct($stringData, Destination_Interface $destination)
{
$this->_string = $stringData;
$this->_destination = $destination;
}
public function __tostring()
{
return $this->_destination->clean($this);
}
public function length()
{
return strlen($this->_string);
}
public function getRaw()
{
return $this->_string;
}
public function setRaw($raw)
{
$this->_string = $raw;
}
public function append(self $str)
{
$new = clone $this;
$new->setRaw($this->getRaw() . $str->getRaw());
return $new;
}
}
Interface Destination_Interface
{
function clean(Str $str);
}
class HtmlDest implements Destination_Interface
{
public function clean(Str $str)
{
return htmlspecialchars($str->getRaw(), ENT_QUOTES);
}
}
$a = new Str('<a>', new HtmlDest());
$b = new Str('<b>k', new HtmlDest());
echo $a->append($b);