kanyjoz/sessions

基于PSR-15中间件的会话处理器

1.0.0 2024-05-18 14:59 UTC

This package is auto-updated.

Last update: 2024-09-18 16:10:13 UTC


README

基于PSR-15中间件的会话处理器

要求

  • PHP 8.3+

安装

composer require kanyjoz/sessions

描述

这是一个基于Cookie的会话处理器,您可以使用PSR-15中间件轻松将其集成到Slim 4+项目中。这是一个个人项目,主要是为了学习和练习,大部分基于https://github.com/odan/session,所以大部分功劳归他。我想创建一些我可以用来自学代码,并公开在github仓库中,以便其他人可以指出我的错误,我可以学习如何进行开源贡献。

Slim 4集成

<?php

use DI\Container;
use Slim\Factory\AppFactory;
use KanyJoz\Sessions\Session;
use KanyJoz\Sessions\SessionConfig;
use KanyJoz\Sessions\Interface\SessionInterface;
use KanyJoz\Sessions\Interface\SessionManagerInterface;
use KanyJoz\Sessions\Interface\FlashInterface;
use KanyJoz\Sessions\Middleware\SessionStartMiddleware;


// Create Container using PHP-DI
$container = new Container();

// Set container to create App with on AppFactory
AppFactory::setContainer($container);

// Configure DI container using SessionConfig object
$container->set(Session::class, function() {
    return new Session(new SessionConfig());
});

// Also register 3 interfaces that you use to interact with your session
$container->set(SessionManagerInterface::class, function(Session $session) {
    return $session; // to start, stop your session
});
$container->set(SessionInterface::class, function(Session $session) {
    return $session; // to put, get session values
});
$container->set(FlashInterface::class, function(Session $session) {
    return $session; // to put, get flash values
});

// Create the application
$app = AppFactory::create();

// Register the middleware to automatically start and stop your session on each request
$app->add(new SessionStartMiddleware());

// Handle incoming HTTP requests
$app->run();

SessionConfig

以下值被用于并传递给配置会话和会话cookie。

<?php

// Session Cookie Config
private int $lifetime = 3600; // 1 hr
private string $path = '/';
private string $domain = '';
private bool $secure = false; // Should be true for production with HTTPS connection
private bool $httponly = true;
private string $samesite = 'Lax'; // Should be Strict in production

// Session Config
private string $name = 'PHPSESSID';
private int $sid_length = 32; // Should be 96 in production
private int $sid_bits_per_character = 4; // Should be 6 in production
private bool $use_strict_mode = false; // Should be true in production
private string $cache_limiter = 'nocache';
private string $referer_check = ''; // Should be set if domain is set

如果您在生产环境中或者想要更改一些默认值:每个值都有getter和fluid setter。

<?php

use KanyJoz\Sessions\Session;
use KanyJoz\Sessions\SessionConfig;

//...

$container->set(SessionConfig::class function() {
    return (new SessionConfig())
        ->setSamesite('Strict')
        ->setSecure(true)
        ->setSidLength(96)
        ->setSidBitsPerCharacter(6);
});

$container->set(Session::class, function(SessionConfig $config) {
    return new Session($config);
});

许可证

MIT