定制 responsive-sk/slim4-session 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

responsive-sk/slim4-session

Composer 安装命令:

composer require responsive-sk/slim4-session

包简介

Complete session management for Slim 4 with zero dependencies and full type safety

README 文档

README

Complete session management for Slim 4 with zero external dependencies and full type safety.

Features

  • Zero Dependencies - No external session libraries required
  • Type Safety - Full PHPStan level max compatibility with @throws annotations
  • Flash Messages - Built-in flash message support with dedicated interface
  • Factory Pattern - Easy configuration for different environments
  • Native PHP Sessions - Direct PHP session management with enhanced interface
  • Custom Storage Engines - Redis, Database, and custom storage support
  • PSR-15 Middleware - Ready-to-use middleware for Slim 4
  • Auto-Refresh - Automatic session lifetime extension on user activity
  • Production Ready - Secure defaults and best practices

Installation

composer require responsive-sk/slim4-session

Quick Start

Basic Usage

use ResponsiveSk\Slim4Session\SessionFactory;

// Create session manager
$session = SessionFactory::create();

// Start session
$session->start();

// Set data
$session->set('user_id', 123);
$session->set('username', 'john_doe');

// Get data
$userId = $session->get('user_id');
$username = $session->get('username', 'guest');

// Check if key exists
if ($session->has('user_id')) {
    echo 'User is logged in';
}

// Flash messages
$session->flash('success', 'Login successful!');
$message = $session->getFlashMessage('success');

// Advanced flash usage
$flash = $session->getFlash();
$flash->add('error', 'Something went wrong');
$errors = $flash->consume('error'); // Get and clear

// Session management
$sessionId = $session->getId();
$session->regenerateId();
$session->destroy();

Environment-Specific Configuration

// Production (secure settings)
$session = SessionFactory::createForProduction([
    'name' => 'my_app_session',
    'cache_expire' => 180,
]);

// Development (relaxed settings)
$session = SessionFactory::createForDevelopment([
    'name' => 'dev_session',
]);

// Testing (no cookies)
$session = SessionFactory::createForTesting();

Custom Configuration

$session = SessionFactory::create([
    'name' => 'custom_session',
    'cookie_lifetime' => 3600,
    'cookie_secure' => true,
    'cookie_httponly' => true,
    'cookie_samesite' => 'Strict',
]);

Complete Interface

Our SessionInterface provides complete session management:

interface SessionInterface extends \Countable, \IteratorAggregate
{
    // Core session methods
    public function set(string $key, mixed $value): void;
    public function get(string $key, mixed $default = null): mixed;
    public function remove(string $key): void;
    public function has(string $key): bool;
    public function all(): array;
    public function clear(): void;

    // Session lifecycle
    public function isStarted(): bool;
    public function start(): bool;
    public function destroy(): bool;

    // Session ID management
    public function getId(): ?string;
    public function regenerateId(): bool;
    public function getName(): string;
    public function setName(string $name): void;

    // Flash messages
    public function flash(string $key, mixed $value): void;
    public function getFlash(): FlashInterface;
    public function getFlashMessage(string $key, mixed $default = null): mixed;
    public function hasFlash(string $key): bool;
}

Architecture

Native Implementation

The package provides a complete native PHP session implementation:

ResponsiveSk\Slim4Session\SessionManager
    ↓ implements
ResponsiveSk\Slim4Session\SessionInterface
    ↓ uses
Native PHP $_SESSION + FlashManager

Factory Pattern

SessionFactory::create()                    // Default config
SessionFactory::createForProduction()      // Production config
SessionFactory::createForDevelopment()     // Development config
SessionFactory::createForTesting()         // Testing config
SessionFactory::createWithConfig()         // Custom config

Security Features

Secure Defaults

  • HttpOnly cookies - Prevents XSS attacks
  • Secure cookies - HTTPS only in production
  • SameSite protection - CSRF protection
  • Strict mode - Prevents session fixation
  • Session regeneration - Built-in ID regeneration

Production Configuration

$session = SessionFactory::createForProduction([
    'cookie_secure' => true,        // HTTPS only
    'cookie_httponly' => true,      // No JavaScript access
    'cookie_samesite' => 'Strict',  // CSRF protection
    'use_strict_mode' => true,      // Session fixation protection
]);

Testing

// Create test session (no cookies)
$session = SessionFactory::createForTesting();

// Test session functionality
$session->set('test_key', 'test_value');
$this->assertEquals('test_value', $session->get('test_key'));

Integration with Slim 4

DI Container Setup

use ResponsiveSk\Slim4Session\SessionFactory;
use ResponsiveSk\Slim4Session\SessionInterface;

return [
    SessionInterface::class => function () {
        return SessionFactory::createForProduction();
    },
];

Middleware Usage

use ResponsiveSk\Slim4Session\SessionInterface;

class SessionMiddleware
{
    public function __construct(
        private readonly SessionInterface $session
    ) {}
    
    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        if (!$this->session->isStarted()) {
            $this->session->start();
        }
        
        return $handler->handle($request);
    }
}

Type Safety

Full PHPStan level max compatibility:

/** @var SessionInterface $session */
$session = SessionFactory::create();

// Type-safe operations
$userId = $session->get('user_id', 0);        // mixed
$username = $session->get('username', '');     // mixed
$data = $session->all();                       // array<string, mixed>
$hasKey = $session->has('key');                // bool

Compatibility

  • PHP 8.3+
  • Slim 4
  • Zero external dependencies
  • PHPStan level max

License

MIT License. See LICENSE for details.

Made with ❤️ by Responsive SK

responsive-sk/slim4-session 适用场景与选型建议

responsive-sk/slim4-session 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 390 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 06 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「middleware」 「session」 「slim」 「type-safe」 「zero-dependencies」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 responsive-sk/slim4-session 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 responsive-sk/slim4-session 我们能提供哪些服务?
定制开发 / 二次开发

基于 responsive-sk/slim4-session 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 390
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 21
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-06-21