4

I'm using Yii2's DBSession class to store web application sessions into a database table, called session.

This table by default only has 3 columns - id, expire and data.

I'd like to store additional information into this table, like the user_id of a logged in user.

Edit: So there's a parent class called yii\web\MultiFieldSession but no examples about how it's used. I'll see what I can discover...

JamesG
  • 1,687
  • 2
  • 25
  • 39

3 Answers3

9

create migration:

$this->createTable('session', [
    'id' => $this->char(40)->notNull(),
    'expire' => $this->integer(),
    'data' => $this->binary(),
    'user_id' => $this->integer()
]);

$this->addPrimaryKey('session_pk', 'session', 'id');

add this to config:

'components' => [
    'session' => [
        'class' => 'yii\web\DbSession',
        'writeCallback' => function($session){
            return [
                'user_id' => Yii::$app->user->id
            ];
        }
        // 'db' => 'mydb',  // the application component ID of the DB connection. Defaults to 'db'.
        // 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
    ],
Vitaly
  • 1,261
  • 2
  • 10
  • 20
  • 1
    Works great, thanks very much. I had the `writeCallback` function in a class extending `DbSession` and just couldn't get it working. Adding the function into the array like this works perfectly. – JamesG Jun 22 '16 at 13:42
  • according documentation should be data MySQL: LONGBLOB, PostgreSQL: BYTEA, MSSQL: BLOB (https://www.yiiframework.com/doc/api/2.0/yii-web-dbsession). For me MSSQL requires datatype nvarchar – Krivers Jul 26 '23 at 17:23
0

Check writeCallBack (a callback that will be called during session data writing)

By Using callback you can set your own database fields.. Used by composeField()

Double H
  • 4,120
  • 1
  • 15
  • 26
0

I didn't want a function in a config file, so I ended up with this:

config/web.php

'components' =>
[
    'session' =>
    [
        'class' => 'app\models\Session',
    ],
],

models/Session.php

class Session extends \yii\web\DbSession
{
    protected function composeFields($id = null, $data = null)
    {
        $fields = parent::composeFields($id, $data);

        $fields['user_id'] = \Yii::$app->user->id;

        return $fields;
    }
}

Sui Dream
  • 530
  • 5
  • 15