When you have some functionality that needs to be shared across multiple controllers, one method is to use action helpers. Action helpers are very powerful and contain hooks to automatically run when you need them too, but you can ignore all that if you don't need it.
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:
<?php class Zend_Controller_Action_Helper_Multiples extends Zend_Controller_Action_Helper_Abstract { function direct($a) { return $a * 2; } }
Note that there is a prefix to the action helper name of Zend_Controller_Action_Helper. You can change this by passing a different prefix as the second parameter to the Zend_Controller_Action_HelperBroker::addPath() call in your bootstrap.
Finally, usage within a controller action:
<?php class IndexController extends Zend_Controller_Action { public function indexAction() { $this->view->headTitle('Home'); $this->view->title = 'Test of the Multiples action helper'; $number = 30; $twice = $this->_helper->multiples($number); $this->view->number = $number; $this->view-twice = $twice; } }
Note that we call the action helper's name as a function of the _helper class. This maps to the direct() call within the helper.
You can put also multiple functions within the action helper:
class Zend_Controller_Action_Helper_Multiples extends Zend_Controller_Action_Helper_Abstract { function direct($a) { return $a * 2; } function thrice($a) { return $a * 3; } }
To call the thrice() function within a controller action you use:
$thrice = $this->_helper->multiples->thrice($number);
As you can see if you use the action helper's name as a property of _helper, then you can call any function within the helper.
This is just a summary to get you going. Full details are in the manual.
Have fun and avoid copy and paste with your common functionality!
Zip Files:
I've created an example project so you can see it in context.
- ZF_Action_Helper_example.zip - 9.7kB
- ZF_Action_Helper_example_with_zf.zip (including ZF 1.6) - 3.5MB


