Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Model view controller 如果用户已登录,则回显不同的菜单_Model View Controller_Authentication_Cakephp 2.0 - Fatal编程技术网

Model view controller 如果用户已登录,则回显不同的菜单

Model view controller 如果用户已登录,则回显不同的菜单,model-view-controller,authentication,cakephp-2.0,Model View Controller,Authentication,Cakephp 2.0,我使用的是cakephp2.0,我试图了解如果用户登录到应用程序中,如何echo动态内容 在视图中我想回显一个菜单来登录或注销用户,我该如何做 // I'm in the default template view if (!AuthComponent::loggedIn()) { $menu = $this->Html->link('Login', array('controller' => 'users', 'action' => 'login'));

我使用的是
cakephp2.0
,我试图了解如果用户登录到应用程序中,如何
echo
动态内容

视图中
我想回显一个菜单来登录或注销用户,我该如何做

// I'm in the default template view
if (!AuthComponent::loggedIn()) {
    $menu  = $this->Html->link('Login', array('controller' => 'users', 'action' => 'login'));
    $menu .= $this->Html->link('Register',  array('controller' => 'users',  'action' => 'register'));
} else {
    $menu  = $this->Html->link('Home', array('controller' => 'users', 'action' => AuthComponent::user('id'), AuthComponent::user('username')));
    $menu .= $this->Html->link('Logout', array('controller' => 'users', 'action' => 'logout'));
}
echo $menu;
我曾想过这样的事情,但我读过它打破了MVC规则

我应该如何在CakePHP中做这样的事情?
是否存在一些联机示例?

使用不同的布局,一个用于访问者,另一个用于登录用户

您可以在app_controller.php中放置类似的内容

    function beforeFilter() {
        if( $this->Auth->user() ){
            $this->layout = 'members';
        }
   }

您可以设置它们是否登录到控制器中,然后相应地使用该元素

在控制器中:

function beforeFilter() {
    if($this->Auth->loggedIn()) {
        $userBar = 'memberBar';
    } else {
        $userBar = 'guestBar';
    }
    $this->set('userBar', $userBar);
}
在布局中:

<?php echo $this->element($userBar); ?>
可以将AuthComponent数据传递给元素,以避免在布局中使用对象

echo $this->Html->link('Home', array('controller' => 'users', 'action' => AuthComponent::user('id'), AuthComponent::user('username')));
echo $this->Html->link('Logout', array('controller' => 'users', 'action' => 'logout'));