PHPackages                             responsive-sk/slim4-session - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. responsive-sk/slim4-session

ActiveLibrary[HTTP &amp; Networking](/categories/http)

responsive-sk/slim4-session
===========================

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

2.3.2(3mo ago)13901MITPHPPHP ^8.3

Since Jun 20Pushed 3mo agoCompare

[ Source](https://github.com/responsive-sk/slim4-session)[ Packagist](https://packagist.org/packages/responsive-sk/slim4-session)[ RSS](/packages/responsive-sk-slim4-session/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (5)Versions (12)Used By (1)

ResponsiveSk Slim4 Session
==========================

[](#responsivesk-slim4-session)

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

**Features**
------------

[](#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**
----------------

[](#installation)

```
composer require responsive-sk/slim4-session
```

**Quick Start**
---------------

[](#quick-start)

### **Basic Usage**

[](#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**

[](#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**

[](#custom-configuration)

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

**Complete Interface**
----------------------

[](#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**
----------------

[](#architecture)

### **Native Implementation**

[](#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**

[](#factory-pattern)

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

**Security Features**
---------------------

[](#security-features)

### **Secure Defaults**

[](#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**

[](#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**
-----------

[](#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**
---------------------------

[](#integration-with-slim-4)

### **DI Container Setup**

[](#di-container-setup)

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

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

### **Middleware Usage**

[](#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**
---------------

[](#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
$hasKey = $session->has('key');                // bool
```

**Compatibility**
-----------------

[](#compatibility)

- **PHP 8.3+**
- **Slim 4**
- **Zero external dependencies**
- **PHPStan level max**

**License**
-----------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

---

**Made with ❤️ by [Responsive SK](https://responsive.sk)**

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance81

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~26 days

Recently: every ~58 days

Total

10

Last Release

100d ago

Major Versions

v1.0.0 → 2.0.02025-06-21

### Community

Maintainers

![](https://www.gravatar.com/avatar/a9ca94d5516a8f930325df47de8418a33caf484280105d108a693533c73d4699?d=identicon)[evan70](/maintainers/evan70)

---

Top Contributors

[![evan70](https://avatars.githubusercontent.com/u/67433?v=4)](https://github.com/evan70 "evan70 (9 commits)")

---

Tags

phpmiddlewareslimsessiontype-safezero-dependencies

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/responsive-sk-slim4-session/health.svg)

```
[![Health](https://phpackages.com/badges/responsive-sk-slim4-session/health.svg)](https://phpackages.com/packages/responsive-sk-slim4-session)
```

###  Alternatives

[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[openswoole/core

Openswoole core library

181.1M32](/packages/openswoole-core)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[jimtools/jwt-auth

PSR-15 JWT Authentication middleware, A replacement for tuupola/slim-jwt-auth

20142.3k3](/packages/jimtools-jwt-auth)[tkhamez/slim-role-auth

Role-based authorization for the Slim framework

1410.3k](/packages/tkhamez-slim-role-auth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
