传统PHP开发网站时,经常会有一些需要公用的自定义函数,通常将它们存放在fun.php中,在需要时include该文件。但是这样通常会include进来很多多余的函数。Zend Framework框架开发时,也会有很多公用函数,有些程序员通过扩张Zend_Controller_Action为My_Controller_Action,将这些公用函数写在My_Controller_Action中,这样,所有的controller都可以使用公用函数。但是这造成了继承冗余。比较好的一个方法是,将每个公用函数写成一个Helper。
The first thing you need to do is decide where to put them. The latest default project structure document recommends using a sub folder from your controllers directory. That is: application/controllers/helpers, and it’s as good a place as any.
Firstly, you need to tell the helper broker where your action helpers are. I usually do this in the bootstrap, but it could equally be done in a front controller plug-in:
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH .'/controllers/helpers');
You then need to create your action helper, we’ll call it Multiples in this example and so
the filename is application/controllers/helpers/Multiples.php:
Zend_Controller_Action_Helper的使用方法简介:
轻击查看英文原文
1. 入口文件代码
首先添加助手路径,比较常用的路径为:application/controllers/helpers。
Zend_Controller_Action_HelperBroker::addPath( APPLICATION_PATH .'/controllers/helpers'); |
2.创建助手类
假设,创建一个乘法助手。助手类名Zend_Controller_Action_Helper_Multiples,Zend_Controller_Action_Helper_为前缀,Multiples为助手名,
文件位置为:application/controllers/helpers/Multiples.php,文件名必须与助手名一致。
class Zend_Controller_Action_Helper_Multiples extends Zend_Controller_Action_Helper_Abstract{ function direct($a) { return $a * 2; } function thrice($a) { return $a * 3; } } |
其中direct()方法将被默认调用,即,$this->_helper->multiples()就会调用direct()方法。
3.在controller中使用
class IndexController extends Zend_Controller_Action { public function indexAction() { $number = 30; $twice = $this->_helper->multiples($number); $thrice = $this->_helper->multiples->thrice($number); $this->view->number = $number;//30 $this->view->twice = $twice;//60 $this->view->thrice = $thrice;//90 }} |
——————————————–
|