FYI: David Mytton of Olate Ltd has written a great introduction to and review of Savant over at SitePoint. Thanks, David! :-)

And now, back to our regularly-scheduled blog entry:

After a bit of kerfluffle over cross-site scripting attacks, and working to sanitize some template output, I realized it how useful it would be for Savant to help automate escaping of values for output. After a few days of mailing-list discussion about how such functionality should work, I've released Savant 2.4.0 with a handful of new methods built-in:

  • setEscape() and addEscape() to define what callbacks to use when escaping output
  • getEscape() to retrieve the array of escaping callbacks
  • $this->escape() to escape-and-return a value
  • $this->_() to escape-and-echo a value

The default escaping callback is htmlspecialchars(), but you can add any number of your own. For example, after instantiating Savant, you can do something like this:

$savant =& new Savant2();
$savant->setEscape(
    'strip_tags',
    'htmlspecialchars',
    array('StaticClass', 'method'),
    array($objectInstance, $objectMethod)
);

Each of the parameters is callback suitable for call_user_func(), and you can use an arbitrary number of parameters.

These callbacks are applied, in order, whenever you use the $this->_() or $this->escape() methods in your Savant templates (which are, of course, just PHP scripts dedicated to presentation logic). For example, instead of echo htmlspecialchars($this->value), you would call $this->_($this->value) (and the default htmlspecialchars escaping will be applied).

In addition, you can override the default escaping. You may optionally pass an arbitrary number of added parameters to escape() or _(), and these will be treated as callbacks to apply to the value instead of the default escaping callbacks. For example, $this->_($this->value, 'strip_tags', 'my_escape_function', array('StaticClass', 'method')) will override the default escaping with the callbacks listed as the added parameters.

Update: The documentation on the Savant site has been updated: all examples using "echo" have been changed to "$this->_()", and the escaping methods themselves have also been documented.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving you codebase, all while keeping it running the whole time.