class UsersController extends AppController {
function index() {
loadHelper('Html');
$html = new HtmlHelper();
debug($html->link('Cake!', 'http://cakephp.org'));
}
}
It works pretty well for most simple helpers. For some complex helpers, however, this is not sufficient. For example, helper Ajax uses helpers Html, Javascript, and Form. If you just write your code as above, you will get fatal errors, saying call a member function on a non-object, from the Ajax helper file /cake/libs/view/helpers/ajax.php. After tracing the code, I found the line in ajax.php is like below,
$this->Javascript->codeBlock($code);
To fix this, I wrote a function loadHelper() to the call AppController. This function also wraps the statement of instantiating the new helper object.
class AppController extends Controller {
function &loadHelper($helper_name) {
loadHelper($helper_name);
$helper_class_name = $helper_name.'Helper';
$helper = new $helper_class_name();
if (isset($helper->helpers) && !empty($helper->helpers)) {
foreach ($helper->helpers as $external_helper) {
$helper->$external_helper =&
$this->loadHelper($external_helper);
}
}
return $helper;
}
}
In the controller using helpers, you may use the below code to load the helper,
$ajax =& $this->loadHelper('Ajax');
and then use the variable $ajax as in views.
At last, using helpers in controllers should be the last choice since it violates the basic rules of MVC.