This post originated from an RSS feed registered with PHP Buzz
by Stephan Schmidt.
Original Post: 19 Data filters for patForms 13
Feed Title: a programmer's best friend
Feed URL: http://blog.php-tools.net/rss.php?version=1.0
Feed Description: The blog of PHP Application Tools
cee
Inspired by Helgi's comment on patForms, I started a new approach to data filters in patForms.
patForms data filters are fore more powerful than input filters in other form processing tools, liek QuickForm. The possibilities of filters include:
Filters work in two directions, e.g. you can store seconds in database and let the user view and enter hours by applying a multiplier filter
Filters can be applied before data is validated, I call these HTTP filters, as they sit between the browser and patForms
Filters can be applied after data is validated, I call these PHP filters, as they sit between patForms and your application
Although this made filters an extremely cool feature, they are harder to use than filters in QuickForm, as each filter (indepentent of the real complexity) has to be an object and needs to be instantiated before it can be used, which led to the following code: <?php
// create the trim filter
$filter =& patForms::createFilter( 'Trim' );
// get the element
$el =& $form->getElementByName( 'username' );
// apply the filter to the element
$el->applyFilter( $filter );
?>
Helgi complained that in most cases you'll probably just want to apply a built-in PHP function to the date that is sent from the user and that having to instantiate objects is overkill for this simple feature.
Today a nice idea popped to my mind: I created a new filter object that is able to apply any PHP function to the form data. Furthermore I created a wrapper function in the element base class which lets you instantiate and configure this object in a single method call. This reduces the necessary code while still maintaining the flexibilty we introduced by using filter objects: <?php
// get the element
$el =& $form->getElementByName( 'username' );
// apply an HTTP filter for incoming data
$el->applySimpleFilter('strtolower');
?>
In addition to a function that filters incoming data, you may pass a second function that modifies the value before it is sent back to the browser. Of course applySimpleFilter() also accepts static methods or object methods instead of functions.
17