我在AppController中查询了User表,如下所示
<?php
class AppController extends Controller {
public function beforeFilter() {
function beforeFilter() {
parent::beforeFilter();
if ($this->Session->read('Auth.User.id')) {
$userLoginInfo = $this->User->findByUserId($this->Session->read('Auth.User.id'));
$this->set('userLoginInfo', !empty($userLoginInfo) ? $userLoginInfo : NULL);
}
}
}
}
?>$userLoginInfo在所有ctp文件中都可用,但我也想在所有其他控制器操作中访问它。
发布于 2015-06-29 13:54:52
现在将此代码放在AppController中
function beforeFilter(){
$this->set(‘accesstest’ , ‘abc’);
}我们必须在其他控制器文件中使用它,比如anotherController.php
然后我们将使用$this->viewVars。
在这里,我们将使用
$test = $this->viewVars[‘accesstest’];
$this->set('test',$test);发布于 2015-06-29 16:12:11
如果想要为所有视图设置一个变量,则可以使用Your own answer,但这不是您在问题中所问的问题。
如果您正确地扩展了AppController,那么您可以创建AppController类的属性,然后可以从任何扩展它的控制器访问该属性:
class AppController extends Controller {
public $accesstest = 'abc';
}然后,在任何扩展AppController的控制器中,您可以使用:
$test = $this->accesstest;
echo $test; // 'abc'但是,如果您想要共享一个可以从所有可以更改的控制器访问的变量,并且希望记住更改,则使用会话:-
$this->Session->write('accesstest', 'abc');
$test = $this->Session->read('accesstest');发布于 2017-04-19 18:12:12
$userLoginInfo = $this->viewVars['userLoginInfo'];https://stackoverflow.com/questions/31108690
复制相似问题