Yii如何getState()并显示变量

时间:2014-10-31 09:24:43

标签: php yii

我正在登录,结果运行正常。但是,我希望从DB获取用户的名字和姓氏。

我知道getState()能够从DB中获取变量数据。

以下是登录的代码:

$username = $_POST['username'];
$userpass = $_POST['userpass']; 


$record=Games::model()->findByAttributes(array('email'=>$username));

if($record===null){
    //somethings
}else if($this->checkPassword($record->password,$userpass)){
    //somethings

}else
{
    $this->_id=$record->id;
    $this->_email=$record->email;

    Yii::app()->user->setState('id', $record->id);
    Yii::app()->user->setState('email', $record->email);
    Yii::app()->user->setState('firstname', $record->firstname);
    Yii::app()->user->setState('lastname', $record->lastname);

    //go to somethings
}

在视图中

<?php 
    $username_first = Yii::app()->user->getState('firstname');
    $username_last  = Yii::app()->user->getState('lastname'); 
?>
    <a href="#" ><?php echo $username_first.' '.$username_last; ?></a>

我的代码在视图中有什么问题?对 getState()我需要的数据有什么更好的建议吗?

已更新:

我尝试在控制器中打印出来......它有效......但为什么看不到?

print_r(Yii::app()->user->getState('firstname'));

1 个答案:

答案 0 :(得分:3)

getState()并非致力于从数据库中获取变量。正如Yii的官方文件所定义的那样:

  

返回存储在用户会话中的变量的值。

通过设置状态,您可以将变量的值存储到用户会话中,并且可以通过getState()获取该值。

作为建议,当您使用getState()时,将默认值传递给第二个参数,如下所示:

$email=Yii::app()->user->getState('email',NULL);
if(!is_null($email)) //do something

最好在hasState()之前检查状态,如下所示:

if(Yii::app()->user->hasState('email')){
     $email=Yii::app()->getState('email',NULL);
}

另一个注意事项是,最好在Controller中获取存储的值并将它们传递给视图,而不是让它们在视图中。看看:

<强>控制器

$email=Yii::app()->user->getState('email'); //it is better to check it via has state, and also passing a default value 
$this->render('view',array(
    'userEmail'=>$email
));

查看

<h2><?php echo $email; ?></h2>

<强>更新

您可能需要将存储的值存入会话(setState()),所以您可以在下面查看:

if(Yii::app()->user->hasState('firstname')) { echo Yii::app()->user->getState('firstname'); } //All done