如果您需要在用户登录时不会发生变化的信息,您应该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;