>我有 yii 项目,在 Chrome 会话中丢失了。例:在主配置.php
'session' => array(
'class' => 'CDbHttpSession',
'autoStart' => false,
'connectionID' => 'db',
'sessionTableName' => 'ph_YiiSession',
'autoCreateSessionTable' => false // for performance reasons
),
登录后在启动控制器中,我在会话中写入ID用户
Yii::app()->user->id = 100
重定向用户后
$this->redirect(array('student/index'), true);
但是在索引操作中,我无法从会话中获取数据
echo Yii::app()->user->id;
什么都不给。请帮忙,这个问题已经让我的大脑崩溃了
你应该试试
'autoStart' => true,
Yii::app()->user->id = 100
首先,
您不能像这样永久设置可以在不同页面中使用的 Id。即使您将在页面中设置Id,一旦移动到下一页,其数据也会丢失,并且将显示其默认值。因此,如果要更改Yii::app()->user->id
包含的值,则必须覆盖getId()方法。
第二件事如果您
尝试在会话中保存 ID,则应使用 Yii::app()->session['_myId']=Yii::app()->user->id;
然后你可以得到它像
echo Yii::app()->session['_myId'];
并记住'autoStart' => TRUE,
你做错的肯定是在UserIdentity类中。从 Yii::app()->user->id
设置和检索会话数据的最佳方法是重写 UserIdentity 类中的 getId()
方法。
例如,假设您有一个名为"User"的表,其中包含:id,用户名,密码。
因此,使UserIdentity类如下所示:
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}else if($user->password !== crypt($this->password,$user->password)){
$this->errorCode = self::ERROR_PASSWORD_INVALID;
}
else{
$this->_id = $user->id;
$this->username = $user->username;
$this->errorCode = self::ERROR_NONE;
}
return $this->errorCode === self::ERROR_NONE;
}
public function getId()
{
return $this->_id;
}
}
完成此操作后,您应该能够使用 Yii::app()->user->id 并在代码中的任何位置获取会话 ID。
希望这有帮助。
附言>我还制作了一个基本应用程序,所有这些都已经完成。您可以在以下位置查看:https://github.com/sankalpsingha/yii-base-app 它可能会对您有所帮助。