您好,我正在使用yii与yii-user-management扩展
我可以看到如何相当简单地获得一些当前登录的用户信息,这些信息存储在用户表中(例如Yii::app()->user->name)
然而,我想知道如何才能获得当前登录用户的相关数据(例如,存储在配置文件表中的用户电子邮件)
在YumUser.php模型文件中有一个关系
$relations['profile'] = array(self::HAS_ONE, 'YumProfile', 'user_id');
然而,我不确定如何使用这个直接在视图文件
我相信YUM文档建议了一种更简洁的方法。在YumWebUser中有一个data()方法,它使用户模型可以从WebUser实例访问:
// Use this function to access the AR Model of the actually
// logged in user, for example
public function data() {
if($this->_data instanceof YumUser)
return $this->_data;
else if($this->id && $this->_data = YumUser::model()->findByPk($this->id))
return $this->_data;
else
return $this->_data = new YumUser();
}
所以,你应该能够简单地使用:
<?php echo Yii::app()->user->data()->profile->firstname; ?>
<?php echo Yii::app()->user->data()->profile->email; ?>
如果您需要在用户登录时不会变化的信息,则应该在登录时使用setState()
函数。
的例子:
class MySqlUserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->findByAttributes( array( 'username' => $this->username ) );
if( $user === null )
$this->errorCode = self::ERROR_USERNAME_INVALID;
else if( $user->password !== md5( $this->password ) )
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else
{
$this->_id = $user->id;
$this->setState( 'username', $user->username );
$this->setState( 'name', $user->name );
$this->setState( 'surname', $user->surname );
$this->setState( 'email', $user->email );
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
这样信息就保存在会话中,你就不需要每次都访问数据库了。
的例子:
echo Yii::app()->user->email;
ok find out myself
在控制器文件的动作中,我应该放入
$user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;
$this->render('index', array('user_profile' => $user_profile));
然后从视图
<?php echo $user_profile->firstname ?>
<?php echo $user_profile->email ?>