11.2. Filter Chains

Often multiple filters should be applied to some value in a particular order. For example, a login form accepts a username that should be only lowercase, alphabetic characters. Zend_Filter provides a simple method by which filters may be chained together. The following code illustrates how to chain together two filters for the submitted username:

<?php
// Provides filter chaining capability
require_once 'Zend/Filter.php';

// Filters needed for the example
require_once 'Zend/Filter/Alpha.php';
require_once 'Zend/Filter/StringToLower.php';

// Create a filter chain and add filters to the chain
$filterChain = new Zend_Filter();
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());

// Filter the username
$username = $filterChain->filter($_POST['username']);

Filters are run in the order they were added to Zend_Filter. In the above example, the username is first removed of any non-alphabetic characters, and then any uppercase characters are converted to lowercase.

Any object that implements Zend_Filter_Interface may be used in a filter chain.