在default.ctp中显示当前登录用户的最佳方法?

时间:2010-09-26 23:14:45

标签: authentication cakephp controller

我正在自定义default.ctp文件,我正在尝试在页面顶部显示当前登录的用户名。

app_controller.php中,我有以下内容:

function beforeFilter()
{
    $user = $this->Auth->user();

    if($user != null)
    {
        $this->Session->write('user_name',$user['User']['username']);
    }
}

default.ctp,我有:

$user = $this->Session->read('Auth.User');

if(!empty($user))
{
    echo 'Hello, ' . $user['user_name'];
}

但是,似乎值$user_name未在任何地方设置。

我做错了什么?有没有更好的方法来实现这一目标?


更新:我已按照答案中的说明对其进行了修改,但仍然无效。我收到一个错误:

  

未定义索引:user_name [APP / views / layouts / default.ctp,第21行]

2 个答案:

答案 0 :(得分:12)

您也可以直接在view / layout

中使用SessionHelper
$user = $this->Session->read('Auth.User');
if(!empty($user)) {
    echo 'Hi ', $user['user_name'];
}

答案 1 :(得分:-2)

$user = $this->Session->read('Auth.User');
 if(count($user)) 
           echo $user['name'];