mipotech/yii2-persistent-session

实现持久化、服务器端会话(“服务器端cookie”)的简单类

1.0.3 2018-05-02 14:40 UTC

This package is auto-updated.

Last update: 2024-09-06 23:51:51 UTC


README

此包提供了一种简单的方式来实现持久化会话,也称为“服务器端cookie”。

安装

安装此扩展的首选方式是通过 composer

只需将此行

"mipotech/yii2-persistent-session": "*",

添加到您的 composer.json 文件的 require 部分并执行 composer update。

配置

在 @app/config/web.php 中将 persistentSession 添加为应用程序组件

'components' => [
    ...
    'persistentSession' => [
        /* Required settings */
        'class' => 'mipotech\persistentsession\PersistentSession',
        
        /* Optional settings */
        //'db' => '...',            // MongoDB application component. Defaults to 'mongodb'
        //'collection' => '...',    // The name of the collection to store the session data. Defaults to 'persistent_session'
        //'cookieClass' => '...'    // The class to used to generate a new cookie. Defaults to 'yii\web\Cookie'
        //'cookieKey' => '...',     // The cookie key to use for identifying the persistent session. Defaults to 'session-id'
        //'cookieParams' => '...',  // The default cookie parameters. Defaults to ['httpOnly' => true, 'secure' => true]
        //'uniqidPrefix' => '...',  // The prefix to use for generating a new session identifier. Defaults to ''
    ]
    ...
]

这样就完成了。包已设置完毕,准备就绪。

使用方法

此组件的功能旨在尽可能接近原生 Yii2 会话(API 文档用户指南)。

打开和关闭会话

$persistentSession = Yii::$app->persistentSession;

// check if a session is already open
if ($persistentSession->isActive) ...

// open a session
$persistentSession->open();

// destroys all data registered to a session.
$persistentSession->destroy();

访问会话数据

$persistentSession = Yii::$app->persistentSession;

// get a session variable.
$language = $persistentSession->get('language');

// set a session variable. The following usages are equivalent:
$persistentSession->set('language', 'en-US');

// remove a session variable. The following usages are equivalent:
$persistentSession->remove('language');

// check if a session variable exists. The following usages are equivalent:
if ($persistentSession->has('language')) ...