By default, DbSession stores session data in a DB table named 'session'. This table
must be pre-created. The table name can be changed by setting [[sessionTable]].
The following example shows how you can configure the application to use DbSession:
Add the following to your application config under components:
php
'session' => [
'class' => 'yii\web\DbSession',
'db' => 'mydb',
'sessionTable' => 'my_session',
]
DbSession extends MultiFieldSession, thus it allows saving extra fields into the [[sessionTable]].
Refer to MultiFieldSession for more details.
/** * @depends testReadWrite */ public function testWriteCustomField() { $session = new DbSession(); $session->writeCallback = function ($session) { return ['user_id' => 15]; }; $session->writeSession('test', 'session data'); $query = new Query(); $sessionRow = $query->from('session')->where(['id' => 'test'])->one(); $this->assertEquals('session data', $sessionRow['data']); $this->assertEquals(15, $sessionRow['user_id']); }
/** * Session GC (garbage collection) handler. * Do not call this method directly. * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. * @return boolean whether session is GCed successfully */ public function gcSession($maxLifetime) { if ($this->dbSession) { return $this->dbSession->gcSession($maxLifetime); } else { parent::gcSession($maxLifetime); } }
public function init() { if (is_string($this->db)) { $this->db = Yii::$app->get($this->db); } if (!$this->db instanceof Connection) { throw new InvalidConfigException("DbSession::db must be either a DB connection instance or the application component ID of a DB connection."); } if (!$this->sessionTable) { $this->sessionTable = $this->db->tablePrefix . 'session'; } parent::init(); }
/** * @inheritdoc */ public function init() { parent::init(); $this->createTable(); }