【问题标题】:how to use public variable in helper file of cakephp如何在 cakephp 的帮助文件中使用公共变量
【发布时间】:2014-01-20 09:28:33
【问题描述】:
我在 cakephp 中创建了一个助手,并在 AppController.php 文件中定义了一个全局变量。
AppController.php
public $testVar = null;
我想在我的帮助文件中使用这个变量。怎么会这样?
【问题讨论】:
-
-
不是和here一样的问题吗?在 Helper 中,您可以在控制器中使用 set() 之后使用 $this->_View->getVar('testVar')
标签:
cakephp
controller
cakephp-2.0
helper
【解决方案1】:
您不能在帮助程序中使用该变量,但您也可以
在 AppController 中,将变量放入会话中:Session::write('currentUser', $this->currentUser)。然后您可以使用 SessionHelper 在 Helper 中访问它:$this->Session->read('currentUser')
使用 set 将变量传递给视图:$this->set('currentUser', $this->currentUser)。然后,您可以访问视图中的 $currentUser 变量并将其作为参数传递给您的助手。
顺便说一句,如果它是您需要的登录用户的 ID,并且您正在使用 Auth 组件,那么您已经可以在会话中找到所有用户信息。你可以在你的助手中访问它,如下所示:$this->Session->read('Auth.User.id')
【解决方案2】:
您不需要传递额外的变量。
直接静态访问AuthComponent:
echo AuthComponent::user('username');
等等
注意:这也是无通知的,因为它首先检查是否存在(您需要在此处使用数组手动断言。
【讨论】:
-
PS:如果还是太多打不开,你可以用Auth这样的东西把它剪成Auth::user()。