CakePHP 2.5:设置全局变量

时间:2014-12-15 20:28:17

标签: cakephp

我在我的AppController中设置一个变量'$ loggedIn',以便全局访问以识别登录用户,但只有在我的url调用Users控制器时才会生效。例如,如果您使用url访问users / index,则表明您已登录。如果我访问pages / home,则不会显示登录。在appcontroller和我的视图中的代码(default.ctp)。

控制器/ AppController.php

public function beforeFilter() {
$this->Auth->allow('index', 'view');
$this->set('loggedIn', $this->Session->read('Auth.User'));//fix here
}

查看/布局/ default.thtml中

    <div id="header">
    <div class="top-links">
    <?php if($loggedIn) { //fix here
        echo $this->Html->link('Register', array('controller'=>'users','action'=>'register')); 
        echo '&nbsp;|&nbsp;';
        echo $this->Html->link('Login', array('controller'=>'users','action'=>'login')); 

        } else {
            echo $this->Html->link('My Profile', array('controller'=>'users', 'action' => 'edit', $loggedIn['User']['id']));//fix here
            echo $this->Html->link('Logout', array('controller'=>'users','action'=>'logout'));
        }
    ?>
    </div>
    <a href="/cake"><img src="/img/logo.png" class="top-logo" /></a>
    <?php
        echo $this->element('top_menu');

    ?>

</div>

1 个答案:

答案 0 :(得分:2)

你可能在PagesController中覆盖了beforeFilter。为了让PagesController继续使用AppController-&gt; beforeFilter代码,你需要在PagesController中使用它:

function beforeFilter() {
        parent::beforeFilter();
        //rest of the code for this function
}
相关问题