简体   繁体   English

如何从CakePHP中的控制器访问帮助器?

[英]How to access a helper from the controller in CakePHP?

Well, this is a tricky one, and I'm not really sure it's not breaking the MVC model. 好吧,这是一个棘手的问题,我不确定它是否会破坏MVC模型。

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. 但是,我认为将$section对象作为解析器帮助器内的私有变量传递会更好。 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. 谢谢。

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: 例如,如果您的助手使用HtmlHelper,则必须执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM