alejoluc/lazysession

无需调用session_start()即可使用会话的包。除非请求使用会话,否则不会调用session_start()。

0.1.4 2018-06-25 12:14 UTC

This package is auto-updated.

Last update: 2024-09-10 06:43:26 UTC


README

此包允许您在使用会话时无需担心是否已正确调用session_start()

不需要在每次请求中都使用session_start(),无论该请求是否实际需要会话,此类将在尝试以任何方式访问其数据时自动启动会话。通过避免在不需要会话时调用session_start(),您可以提高服务器资源的利用率,尤其是在默认的会话存储方法为文件系统时,这可能会相对较慢。

该接口与PHP原生使用的接口非常相似,允许您通过方法获取、创建、修改或删除会话数据,或通过使用会话键作为数组键或对象属性。下面是示例说明。

尽管该类提供了使用常见会话功能的方法,例如更改会话存储路径,但不需要从实例化对象中调用这些功能,您也不受已实现方法访问原生功能的限制:由于该类使用原生PHP会话实现,因此您在代码中调用的任何session_*函数都将与该类很好地配合工作。

安装

从命令行

composer require alejoluc/lazysession

或者在composer.json中手动写入

{
  "require": {
    "alejoluc/lazysession": "*"
  }
}

示例用法:在粗略的登录示例中实例化类并访问会话数据

<?php
require __DIR__ . '/vendor/autoload.php';
use alejoluc\LazySession\LazySession;

$session = new LazySession();

$page = isset($_GET['page']) ? $_GET['page'] : 'login';
if ($page === 'login') {
    // Accessing session data using the object oriented interface
    if ($session->get('logged-in') !== true) {
        // For clarity and space purposes, we assume that here a function
        // checking for the existence of an user with request data would be
        // called
        if (true) {
            // Accessing session data via array keys
            $session['logged-in'] = true;
            $session['username']  = 'Test_Username';
            $session['email']     = 'test@email.com';
            
            echo 'You have logged in. Please refresh the page';
        }   
    } else {
        echo "You are logged in, this is your data:<br />";
        // Accessing session data via object properties
        echo "username: " . $session->username . "<br />";
        echo "e-mail: " . $session->email;
    }   
} elseif ($page === '...') {
    // Some page that does not need session data. In this branch of the
    // execution, session_start() will never be called

    // The following code will output the integer 1, which is the value of
    // the constant PHP_SESSION_NONE. That means sessions are enabled
    // but no session has been started
    var_dump(session_status());
} elseif ($page === 'logout') {
    $session->clear();
}

设置、获取和删除

<?php
// Getting: All of the following are equivalent and valid
$value = $session->get('key');
$value = $session['key'];
$value = $session->key;

$value = $session->get('special&char');
$value = $session['special&char'];
$value = $session->{'special&char'};


// Setting: All of the following are equivalent and valid
$session->set('key', 'value');
$session['key'] = 'value';
$session->key   = 'value';

$session->set('special&char', 'value');
$session['special&char'] = 'value';
$session->{'special&char'} = 'value';

// Deleting: All of the following are equivalent and valid
$session->delete('key');
unset($session['key']);
unset($session->key);

删除所有会话数据

<?php
// [...instantiation, code...]
$session->clear();

为下一个请求闪烁数据

熟悉Laravel的人可能会习惯在会话中闪烁数据以供下一个请求使用。这可以通过LazySession实现。

<?php
//[..instantiation..]
if ($app->performAction()) {
    $session->flash('message', 'Everything happened successfully');
    $session->flash('message-type', 'info');
} else {
    $session->flash('message', 'Error: nothing happened');
    $session->flash('message-type', 'error');
}

要在下一个请求中检索闪烁的数据,您可以使用特定的flashGet()方法或使用更通用的get()方法。两种方法都可以。

<?php
//[..instantiation]]
if ($session->has('message')) { // Equivalent to $session->flashHas('message')
    echo '<div class="message-' . $session->get('message-type') . '">' . $session->get('message') . '</div>"';
}

更改会话保存路径

<?php
// [...instantiation, code...]
$session->savePath(__DIR__ . '/tmp/sessions/');
$session->start(); // will create a session file in ./tmp/sessions/

// The following is equivalent, and the class will behave
// as expected after it
session_save_path(__DIR__ . '/tmp/sessions/');
$session->start(); // will create a session file in ./tmp/sessions/