2012-01-01 28 views
0

我正在使用CakePHP 2.0,我試圖瞭解如何在用戶登錄應用程序時使用echo動態內容。如果用戶登錄時回顯不同的菜單

view我想呼應菜單登錄或註銷用戶,我該怎麼做?

// 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中做這樣的事情? 在線是否存在一些示例?

回答

1

如果他們登錄或沒有控制器,然後相應地使用該元素您可以設置。

在你的控制器:

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

在您的佈局:

<?php echo $this->element($userBar); ?> 

然後有一個memberBar元素和guestBar元素:

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')); 

您可以在AuthComponent數據傳遞到要避免在佈局中使用該對象的元素。

0

使用不同的佈局,一個用於訪問者,另一個用於登錄用戶。

你可以把這樣的事情在app_controller.php

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