Class yii\mongodb\Session

Inheritanceyii\mongodb\Session » yii\web\MultiFieldSession
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/src/Session.php

Session extends \yii\web\Session by using MongoDB as session data storage.

By default, Session stores session data in a collection named 'session' inside the default database. This collection is better to be pre-created with fields 'id' and 'expire' indexed. The collection name can be changed by setting $sessionCollection.

The following example shows how you can configure the application to use Session: Add the following to your application config under components:

'session' => [
    'class' => 'yii\mongodb\Session',
    // 'db' => 'mymongodb',
    // 'sessionCollection' => 'my_session',
]

Session extends MultiFieldSession, thus it allows saving extra fields into the $sessionCollection. Refer to MultiFieldSession for more details.

Tip: you can use MongoDB TTL index for the session garbage collection for performance saving, in this case you should set Session::gCProbability to 0.

Public Properties

Hide inherited properties

Property Type Description Defined By
$db yii\mongodb\Connection|array|string The MongoDB connection object or the application component ID of the MongoDB connection. yii\mongodb\Session
$fields array Session fields to be written into session table columns yii\mongodb\Session
$sessionCollection string|array The name of the MongoDB collection that stores the session data. yii\mongodb\Session

Protected Properties

Hide inherited properties

Property Type Description Defined By

Public Methods

Hide inherited methods

Method Description Defined By
destroySession() Session destroy handler. yii\mongodb\Session
gcSession() Session GC (garbage collection) handler. yii\mongodb\Session
init() Initializes the Session component. yii\mongodb\Session
readSession() Session read handler. yii\mongodb\Session
regenerateID() Updates the current session ID with a newly generated one. yii\mongodb\Session
writeSession() Session write handler. yii\mongodb\Session

Property Details

Hide inherited properties

$db public property

The MongoDB connection object or the application component ID of the MongoDB connection. After the Session object is created, if you want to change this property, you should only assign it with a MongoDB connection object. Starting from version 2.0.2, this can also be a configuration array for creating the object.

$fields protected property (available since version 2.1.8)

Session fields to be written into session table columns

protected array $fields = []
$sessionCollection public property

The name of the MongoDB collection that stores the session data. Please refer to yii\mongodb\Connection::getCollection() on how to specify this parameter. This collection is better to be pre-created with fields 'id' and 'expire' indexed.

public string|array $sessionCollection 'session'

Method Details

Hide inherited methods

destroySession() public method

Session destroy handler.

Do not call this method directly.

public boolean destroySession ( $id )
$id string

Session ID

return boolean

Whether session is destroyed successfully

                public function destroySession($id)
{
    $this->db->getCollection($this->sessionCollection)->remove(
        ['id' => $id],
        ['justOne' => true]
    );
    return true;
}

            
gcSession() public method

Session GC (garbage collection) handler.

Do not call this method directly.

public boolean gcSession ( $maxLifetime )
$maxLifetime integer

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)
{
    $this->db->getCollection($this->sessionCollection)
        ->remove(['expire' => ['$lt' => time()]]);
    return true;
}

            
init() public method

Initializes the Session component.

This method will initialize the $db property to make sure it refers to a valid MongoDB connection.

public void init ( )
throws \yii\base\InvalidConfigException

if $db is invalid.

                public function init()
{
    parent::init();
    $this->db = Instance::ensure($this->db, Connection::className());
}

            
readSession() public method

Session read handler.

Do not call this method directly.

public string readSession ( $id )
$id string

Session ID

return string

The session data

                public function readSession($id)
{
    $collection = $this->db->getCollection($this->sessionCollection);
    $condition = [
        'id' => $id,
        'expire' => ['$gt' => time()],
    ];
    if (isset($this->readCallback)) {
        $doc = $collection->findOne($condition);
        return $doc === null ? '' : $this->extractData($doc);
    }
    $doc = $collection->findOne(
        $condition,
        ['data' => 1, '_id' => 0]
    );
    return isset($doc['data']) ? $doc['data'] : '';
}

            
regenerateID() public method

Updates the current session ID with a newly generated one.

Please refer to http://php.net/session_regenerate_id for more details.

public void regenerateID ( $deleteOldSession false )
$deleteOldSession boolean

Whether to delete the old associated session file or not.

                public function regenerateID($deleteOldSession = false)
{
    $oldID = session_id();
    // if no session is started, there is nothing to regenerate
    if (empty($oldID)) {
        return;
    }
    parent::regenerateID(false);
    $newID = session_id();
    $collection = $this->db->getCollection($this->sessionCollection);
    $row = $collection->findOne(['id' => $oldID]);
    if ($row !== null) {
        if ($deleteOldSession) {
            $collection->update(['id' => $oldID], ['id' => $newID]);
        } else {
            unset($row['_id']);
            $row['id'] = $newID;
            $collection->insert($row);
        }
    } else {
        // shouldn't reach here normally
        $collection->insert($this->composeFields($newID, ''));
    }
}

            
writeSession() public method

Session write handler.

Do not call this method directly.

public boolean writeSession ( $id, $data )
$id string

Session ID

$data string

Session data

return boolean

Whether session write is successful

                public function writeSession($id, $data)
{
    if ($this->getUseStrictMode() && $id === $this->_forceRegenerateId) {
        //Ignore write when forceRegenerate is active for this id
        return true;
    }
    // exception must be caught in session write handler
    // http://us.php.net/manual/en/function.session-set-save-handler.php
    try {
        // ensure backwards compatability, related to:
        // https://github.com/yiisoft/yii2/pull/17188
        // https://github.com/yiisoft/yii2/pull/17559
        if ($this->writeCallback && !$this->fields) {
            $this->fields = $this->composeFields();
        }
        // ensure data consistency
        if (!isset($this->fields['data'])) {
            $this->fields['data'] = $data;
        } else {
            $_SESSION = $this->fields['data'];
        }
        // ensure 'id' and 'expire' are never affected by [[writeCallback]]
        $this->fields = array_merge($this->fields, [
            'id' => $id,
            'expire' => time() + $this->getTimeout(),
        ]);
        $this->db->getCollection($this->sessionCollection)->update(
            ['id' => $id],
            $this->fields,
            ['upsert' => true]
        );
        $this->fields = [];
    } catch (\Exception $e) {
        Yii::$app->errorHandler->handleException($e);
        return false;
    }
    return true;
}