How to access a helper from the controller in CakePHP?

风格不统一 提交于 2019-12-07 08:17:34

问题


Well, this is a tricky one, and I'm not really sure it's not breaking the MVC model.

I'm loading some data into the controller, retrieved from the model. I'm passing this object to the view almost in every action. I'm processing this data from a helper and I'm passing the object as an argument:

controller:

$this->('section', $section);

helper:

<h3><?php echo $parser->section_name($section); ?></h3>

However, I think it would be way better if I could pass that $section object as a private variable inside the parser helper. I could do this in the first line of each view:

$parser->section_object = $section;

And each parser method will look something like

function section_name(){
   return $this->section_object['Section']['name'];
}

The question is: is there a way to automatizate this from the controller? Because the controller can't access the helper, I tried creating the helper from the controller and setting the local variable there:

function beforeFilter(){
    $section = $this->Section->getOne();
    App::import('Helper', 'Parser');
    $ParserHelper = new ParserHelper();
    $ParserHelper->section_object = $section;
    $this->set('parser', $ParserHelper);
}

However, if the helper includes some other helpers, they won't be loaded and the helper will trigger a lot of errors.

Thanks.


回答1:


You have to manually create the helpers used by your helper. For example, if your helper uses the HtmlHelper, you have to do something like:

App::import('Helper', 'Html');
$ParserHelper->Html = new HtmlHelper();


来源:https://stackoverflow.com/questions/6497975/how-to-access-a-helper-from-the-controller-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!