How to access a helper from the controller in Cake

2019-05-03 23:14发布

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条回答
走好不送
2楼-- · 2019-05-04 00:03

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();
查看更多
登录 后发表回答