在CakePHP中,如何从助手中调用AppController方法? [英] In CakePHP, how do I call an AppController method from a helper?

查看:267
本文介绍了在CakePHP中,如何从助手中调用AppController方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

后续问题:在CakePHP中,我在哪里可以放置一个方法来检查会话用户?





$背景:在我上一个问题中,我被告知正确的地方放置一个方法,例如 levelCheck()执行用户级别的半复杂评估,并且在几乎所有我的控制器中都需要的是 AppController



现在,这种方法对于设计菜单布局和其他视图设备的方式也非常有用。因为这个原因,我想创建一个帮助程序,可以使用这种方法。



问题:我知道它一般皱眉从视图中调用控制器方法...但是没有可行的方法来传递数据来复制此​​方法的函数,也不想在两个地方复制方法(违反DRY方法)。



问题:我该如何从助手中调用此方法,或者是否有更好的方法在视图/元素中提供此方法?

解决方案

我最终使用的解决方案是将方法移动到一个组件( CurrentUserComponent )。



从那里,就像调用帮助器头部的组件一样简单...

  App :: uses('CurrentUserComponent','Controller / Component'); 

并引用组件的静态方法:

  CurrentUserComponent :: levelCheck(x,y,z); 

我不认为这完全是在MVC模式的意图,它可怕的,并允许从应用程序中的任何地方访问该方法。


Follow up question to: In CakePHP, where would I put a method that performs a check on the Session User?


Background: In my previous question, I was informed that the correct place to place a method such as levelCheck() which performs a semi-complicated evaluation of a user's level, and is needed in practically all my controllers, is the AppController.

Now, this method is also incredibly useful for the way I design menu layouts and other view devices. For that reason, I would like to create a helper that can make use of that method.

Problem: I recognize that it's generally frowned upon to call a controller method from the view... however there is no viable way for me to pass data to replicate the function of this method, nor do I want to replicate the method in two places (violating DRY methodology).

Question: How then do I call this method from a helper, or is there a better way to provide use of this method in the view/elements?

解决方案

The solution I ended up using was to move the method to a component (CurrentUserComponent).

From there, it was as simple as calling the component in the head of my helper...

App::uses('CurrentUserComponent', 'Controller/Component');

And referencing the component's static method:

CurrentUserComponent::levelCheck(x,y,z);

I don't think this is entirely within the intention of the MVC pattern, but it doesn't pervert it horribly, and allows access to the method from anywhere in the application.

这篇关于在CakePHP中,如何从助手中调用AppController方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆