我目前正在登录,结果运行良好。但是,我希望从数据库中获取用户的名字和姓氏。
据我所知,getState() 能够从数据库获取变量数据。
以下是登录代码:
$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
}
在 View 中
<?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() 我需要的数据有更好的建议吗?
更新:
我尝试在 Controller 中打印......它有效......但为什么 View 不能?
print_r(Yii::app()->user->getState('firstname'));
最佳答案
getState()
并不专用于从数据库获取变量。正如 Yii 的官方文档所定义的:
Returns the value of a variable that is stored in user session.
通过设置状态,您可以将变量的值存储到用户 session 中,并且可以通过 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
中存储的值并将它们传递给 View ,而不是将它们放在 View 中。看看:
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>
更新
有一个条件,您可能需要将存储的值放入 session 中(通过setState()
),因此您可以在 View 中执行如下操作:
if(Yii::app()->user->hasState('firstname')) { echo Yii::app()->user->getState('firstname'); } //All done
关于php - Yii 如何 getState() 并显示变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671209/