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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?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.
1 2 3 4 5 |
<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.
1 2 3 4 |
* ONE! * MyTableColumn * this is <b>tag</b> * Second |
History
Date | Content |
---|---|
2008/4/25 | Published |
2008/4/27 | It was modified to filter array. |