Home > General > Creating Custom Filter

Creating Custom Filter

intro
This article shows how to create a custom filter that extends Zend_Filter_Interface. The filter in this article is used for replacing a value with array value.

1.Create Custom Filter
Create the file library/My/Filter/ArrayValue.php with the following content.

<?php
require_once 'Zend/Filter/Interface.php';
 
class My_Filter_ArrayValue implements Zend_Filter_Interface
{
    protected $_list = array();
 
    public function __construct($list = array())
    {
        $this->_list = $list;
    }
 
    public function filter($value)
    {
        if (is_array($value))
        {
            foreach($value as &$element)
            {
                $element = $this->filter($element);
            }
        }
        else if (isset($this->_list[$value]))
        {
            return $this->_list[$value];
        }
        return $value;
    }
}
2.Create Controller
Create the file application/controllers/FilterController.php with the following content.

<?php
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Filter.php';
require_once 'Zend/Filter/Input.php';
 
class FilterController extends Zend_Controller_Action
{
    protected function _getOutputFilter($data)
    {
        $chain = new Zend_Filter();
        $chain->addFilter(new Zend_Filter_StringToLower());
        $list = array('1'=>'First', '2'=>'Second', '3'=>'Third');
        // add other filters
        $filters = array(
            '*' => $chain,
            'number' => array(array('PregReplace', '/^1$/', 'ONE!')),
            'column' => 'Word_UnderScoreToCamelCase',
            'rank' => array(array('ArrayValue', $list))
        );
        $of = new Zend_Filter_Input($filters, null, $data);
        $of->addFilterPrefixPath('My_Filter', 'My/Filter/');
        return $of;
    }
 
    public function indexAction()
    {
        $values = array(
            'number' => '1',
            'column' => 'my_table_column',
            'message' => 'THIS IS <b>TAG</b>',
            'rank' => '2'
        );
        $this->view->of = $this->_getOutputFilter($values);
        $this->view->values = $values;
    }
}
3.Create View
Create the file application/views/script/filter/index.phtml with the following content.

 
<ul>
<?php foreach($this->values as $key => $value) : ?>
<li><?= $this->of->$key ?></li>
 
<?php endforeach; ?>
</ul>
 
3.Result of Execution
Below is the output of view.

    * ONE!
    * MyTableColumn
    * this is <b>tag</b>
    * Second

History
Date Content
2008/4/25 Published
2008/4/27 It was modified to filter array.

Comments:0

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://www.oplabo.com/article/33/trackback
Listed below are links to weblogs that reference
Creating Custom Filter from Open Programming Laboratory

Home > General > Creating Custom Filter

Japanese
Search
Feeds

Return to page top