Adding helpers to your controllers or actions
Nov 7, 2006
I usually have a set of helpers that my view layouts use throughout an entire application. This makes the AppController a great place for putting these helpers in the $helpers array so they are always there. But if you've ever done this, and needed another helper for just one controller or a single action in a controller, then you might have found your solutions a little clunky. You either had to completely overwrite the $helpers array in your controller, or you did something clunky like this: $this->helpers = array_merge(array('HelperName', 'HelperName2', 'HelperName3'), $this->helpers); Obviously not a very quick and clean approach to adding a helper for your view. But what if you could do this? $this->addHelper('HelperName', 'HelperName2', 'HelperName3', 'etc...'); That would probably save some time and the syntax itself better explains exactly what you're doing. So, after doing the array_merge() trick so many times, I finally implemented my own addHelper() method... here it is:<?php
class AppController extends Controller {
function addHelper() {
$this->helpers = array_merge(func_get_args(), $this->helpers);
}
}
?>
Now if a single action needs a helper, you would just use addHelper(). If you want the helper for the entire controller and don't want to overwrite your $helpers array (makes your controller less flexible if your AppController's $helpers array changes) then you would call addHelper() in the beforeFilter(). Much simpler
1 comment





Bret Kuhns