如何从 CakePHP 中的控制器访问助手?
嗯,这是一个棘手的问题,我不确定它是否会破坏 MVC 模型。
我正在将从模型中检索的一些数据加载到控制器中。我几乎在每个动作中都会将这个对象传递给视图。我正在处理来自助手的数据,并将该对象作为参数传递:
controller:
$this->('section', $section);
helper:
<h3><?php echo $parser->section_name($section); ?></h3>
但是,我认为如果我可以将该 $section
对象作为参数传递,那就更好了解析器助手内的私有变量。我可以在每个视图的第一行执行此操作:
$parser->section_object = $section;
每个解析器方法看起来像这样
function section_name(){
return $this->section_object['Section']['name'];
}
问题是:是否有办法从控制器自动执行此操作? 因为控制器无法访问助手,我尝试从控制器创建助手并在那里设置局部变量:
function beforeFilter(){
$section = $this->Section->getOne();
App::import('Helper', 'Parser');
$ParserHelper = new ParserHelper();
$ParserHelper->section_object = $section;
$this->set('parser', $ParserHelper);
}
但是,如果助手包含一些其他助手,它们将不会被加载,并且助手将触发很多错误。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须手动创建助手使用的助手。例如,如果您的助手使用 HtmlHelper,您必须执行以下操作:
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: