2014-01-24 33 views
1
布局

我的变量loggedInAppController被定义在beforeFilter()功能,如下所示:通行证变量CakePHP中

function beforeFilter(){ 
     $this->Auth->loginRedirect = array('controller'=> 'questions', 'action' => 'home'); 
     $this->Auth->logoutRedirect = array('controller'=> 'questions', 'action' => 'home'); 
     $this->Auth->allow('signup', 'confirm', 'home', 'show'); 
     $this->Auth->authorize = 'controller'; 
     $this->Auth->userScope = array('User.confirmed' => '1'); 
     $this->set('loggedIn', $this->Auth->user('id')); 
    } 

在我的布局,我使用下面的测试loggedIn变量的值:

<?php if($loggedIn): ?> 

当我运行该应用程序我得到这个错误:

Undefined variable: loggedIn [APP\View\Layouts\default.ctp 

你能帮助我吗?先谢谢你。

+0

您可以在视图中使用'$ this-> Auth-> user('id')'! –

+0

您还应该在函数内添加'parent :: beforeFilter()'。 (并不是说它会有太大变化) – cornelb

+1

@GilbertoRamos不,这是不可能的,'Auth'是一个组件,而不是视图帮助器。从CakePHP 2开始,可以使用[**'AuthComponent:user()'**](http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-登录用户)。 – ndm

回答

0
function beforeFilter(){ 
     parent::beforeFilter(); 
     $this->Auth->loginRedirect = array('controller'=> 'questions', 'action' => 'home'); 
     $this->Auth->logoutRedirect = array('controller'=> 'questions', 'action' => 'home'); 
     $this->Auth->allow('signup', 'confirm', 'home', 'show'); 
     $this->Auth->authorize = 'controller'; 
     $this->Auth->userScope = array('User.confirmed' => '1'); 
     $this->set('loggedIn', $this->Auth->user('id')); 
    } 

更改您beforeFilter函数add线parent::beforeFilter();,之后在布局文件,你可以使用<?php if($loggedIn): ?>

+1

你确定这是修复吗?我能够将变量发送到视图,即使没有'parent :: beforeFilter()' – cornelb

+0

该场景是代码是不是来beforeFilter函数,我很久以前面临这个问题,这个技巧的作品,以及你的观点是有效的我也能够发送变量到视图文件没有父:: beforeFilter() – Anubhav

+0

它不能与父:: beforeFilter(),我设置变量在usercontroller视图,$ this-> set('loggedIn', $这 - > Auth->用户( 'ID'));它的工作原理,但我仍然不明白为什么变量在前面的代码中是未知的。任何想法? – klark

1

有一种更好的方式来做到这一点。

在你的AppController:

public function beforeFilter() { 
    parent::beforeFilter(); 
    $this->set('loggedIn', $this->Auth->loggedIn()); 
} 

或者,如果你需要访问的loggedIn VAR在控制器和你的观点:

public function beforeFilter() { 
    parent::beforeFilter(); 
    $loggedIn = $this->Auth->loggedIn(); 
    $this->set('loggedIn', $loggedIn); 
} 

这是为什么在beforeFilter()?以便在准备页面之前访问该变量。这将返回一个布尔值,完美的决定,如果用户登录或没有,所以评价它为:

<?php if($logged_in===true): ?> 

如果你仍然需要用户ID或其他用户的属性,然后在您的视图中使用这样的:

$id = $this->Auth->user('id'); 

As on the bottom of this page

在beforeFilter你不会设置单独的属性,如果他们能已经在您的视图访问 - 你想保持控制器用作瘦越好。