PHPackages                             kodus/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. kodus/session

ActiveLibrary

kodus/session
=============

A simple interface for storing and retrieving session data without the use of PHP's native session handling

3.4.0(1mo ago)946.9k↓21.6%2[1 issues](https://github.com/kodus/session/issues)MITPHPPHP &gt;=8.0

Since Dec 7Pushed 1mo ago1 watchersCompare

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

READMEChangelog (6)Dependencies (22)Versions (14)Used By (0)

kodus/session
=============

[](#kodussession)

A simple interface for storing and retrieving session data without the use of PHP's native session handling.

[![PHP Version](https://camo.githubusercontent.com/487804500a039aee09e5d93e41b745b4cd68dcc0fdf801e67d26d30b93f83358/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d382e302532422d626c75652e737667)](https://packagist.org/packages/kodus/session)[![Build Status](https://camo.githubusercontent.com/7d41c1286238cf39255911156f16b6de349f7f8278c8570b4d30116b3014bf41/68747470733a2f2f7472617669732d63692e6f72672f6b6f6475732f73657373696f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/kodus/session)

Installation
------------

[](#installation)

If your project is using composer, simply require the package:

```
composer require kodus/session

```

Introduction
------------

[](#introduction)

This library provides a way of working with session data that promotes type safety and simplicity, without relying on PHP's native session handling.

Type safety is accomplished by gathering the session data into simple session model classes, whose attributes and methods can be type hinted, and storing instances of these in session, rather than storing values individually.

This approach requires an added amount of boilerplate code. The advantage of these session models easily outweighs the small amount of added workload of writing a small and simple data model.

Write operations to the session are deffered until the end of the request, when they are saved to the storage. This prevents broken session states as a result of critical errors.

Starting and ending sessions happens implicitly - for example, a session won't persist (and no session-cookie will be emitted) unless there is any data in the session; likewise, session will automatically terminate if session-data is cleared and/or the last session-model gets garbage-collected.

Session models
--------------

[](#session-models)

When storing data in session, the first step is to define your session model. You can think of a session model class as a container class for your session data.

A good example of a session model could be a user session model. Let's look at a user session, where both the ID and the full name of the user needs to be stored in session:

```
class UserSession implements SessionModel
{
    private $user_id;
    private $full_name;

    public function setUserID(int $user_id)
    {
        $this->user_id = $user_id;
    }

    public function getUserID(): int
    {
        return $this->user_id ?: 0;
    }

    public function setFullName(string $full_name)
    {
        $this->full_name = $full_name;
    }

    public function getFullName(): string
    {
        return $this->full_name ?: "";
    }

    public function isEmpty(): bool
    {
        return empty($this->user_id) && empty($this->full_name);
    }
}
```

These models should be encapsulated to the current domain. In other words, don't be tempted to collect all session data into a big "catch-all" session model.

The interface `SessionModel` only requires you to implement the method `isEmpty()`, so you can define you session models to your preferred style, as long as the following holds true:

- **Instances of `SessionModel` MUST be able to be serialized and deserialized by native PHP serialization functions without loss of data.**
- **Instances of `SessionModel` MUST have a constructor method with no arguments, or default values for all constructor arguments.**

It is strongly encouraged that implementations of `SessionModel` should only have attributes and methods specifically related to storing session data.

`SessionModel::isEmpty(): bool`: This method should only return true when a session models state is the same as when it was first constructed. When serializing the session models this is used for garbage collection, removing empty models from storage.

Session
-------

[](#session)

The interface `Session` defines a locator for your session models. You get session models for the current session by calling the `get` method.

The `get()` method returns a reference to the session model. All changes made to the instance are stored at the end of the request.

```
/** @var UserSession $user_session */
$user_session = $session->get(UserSession::class);
```

#### Session models are always available

[](#session-models-are-always-available)

Only one instance of a session model is available per session, and it is always available. If an instance of the session model was not stored in cache, a new instance will be created and returned by `get()`.

This means you can assume that an instance of the session model is always available.

#### Deleting individual session models

[](#deleting-individual-session-models)

Because session models are always available, you will never delete a session model directly.

Instead, your models must indicate via the `SessionModel::isEmpty()` method whether your model considers itself to be empty - if so, the Session Service will garbage-collect it at the end of the request.

If your individual session model can be "cleared", your model must define what that means - for example, the following model implementation supports a `clear()` method:

```
class UserSession implements SessionModel
{
    private $user_id;

    public function clear()
    {
        unset($this->user_id);
    }

    public function isEmpty(): bool
    {
        return empty($this->user_id);
    }

    // ...
}
```

#### Clearing session state

[](#clearing-session-state)

You can clear an entire session, typically in a log-out controller/action:

```
$session->clear();
```

Note that clearing the session will *orphan* any objects previously obtained via `get()`.

Clearing the session also implicitly renews the session, as described below.

#### Renewing sessions

[](#renewing-sessions)

You can renew an existing session, typically in a log-in controller/action:

```
$session->renew();
```

Renewing a session will *retain* the current session state, but changes the Session ID, and destroys the session data associated with the old Session ID.

Note that periodic renewal of the Session ID is *not* recommended - issuing a new Session ID should be done only after authentication, e.g. after successful validation of user-supplied login credentials over a secure connection.

#### Destroying a specific session

[](#destroying-a-specific-session)

In rare cases, you may wish to destroy a specific session. For example, you may wish to forcibly destroy the active session of a user who has been blocked/banned from the site by an administrator.

You can do this by accessing the underlying `SessionStorage` implementation:

```
$storage->delete($session_id);
```

Note that this requires you to track the active Session ID for your users, which is outside the scope of this package - you could, for example, store the most recent Session ID in a column in your user-table in the database.

If you're using a dependency injection container, you should bootstrap the `SessionStorage` as a separate component, so you can access it independently of the `SessionService`.

#### Flash messages

[](#flash-messages)

A flash message is a message that can only be read once, e.g. notifications. With the session model concept this becomes a trivial task:

```
class Notifications implements SessionModel
{
    private $notifications = [];

    public function add(string $message)
    {
        $this->notifications[] = $message;
    }

    public function take()
    {
        $notifications = $this->notifications;

        $this->notifications = [];

        return $notifications;
    }

    public function isEmpty(): bool
    {
        return count($this->notifications) == 0;
    }
}
```

Middleware
----------

[](#middleware)

The package includes a PSR-15 compliant `SessionMiddleware` for easy integration of `SessionService`.

Either use this with your PSR-15 compatible middleware stack, or use it as reference for making custom middleware that integrates more deeply with the rest of your stack.

Put this near the top of your middleware stack - it will initialize the session state, then delegate unconditionally to the rest of your middleware stack, and finally commits any changes to session storage.

The request will be decorated with a `SessionData` instance, which can be obtained from the request, in lower layers of your middleware stack, using e.g. `$request->getAttribute(SessionMiddleware::ATTRIBUTE_NAME)`.

Session Service
---------------

[](#session-service)

This section details how to integrate `SessionService` into your own stack.

To initialize a session (at the beginning of a request) use the `beginSession()` method, which returns an instance of `SessionData`, which represents the session state for the request you're processing.

`SessionData` implements `Session`, which defines the public facet of `SessionData` - type-hint against `Session`, for example, when providing this (e.g. via constructor-injection) to your controllers.

To commit changes to session state (at the end of a request) use the `commitSession()` method, which also adds a session cookie to a PSR-7 `ResponseInterface` instance.

Refer to `SessionMiddleware` for a working implementation of this pattern.

Storage Adapters
----------------

[](#storage-adapters)

Customizing session storage is possible by implementing the `SessionStorage` interface.

Currently `kodus/session` comes with a `SimpleCacheAdapter`, which depends on an implementation of the PSR-16 cache interface for the physical storage of raw Session Data.

We recommend the [ScrapBook](https://github.com/matthiasmullie/scrapbook) package as a cache provider for `SimpleCacheAdapter`.

Bootstrapping
-------------

[](#bootstrapping)

Here's an example of how to fully bootstrap all layers of the session abstraction, from a `PDO` database connection at the lowest level, over ScrapBook's SQLLite cache provider, to our PSR-16 Session Storage adapter, and finally to PSR-15 middleware:

```
use PDO;
use MatthiasMullie\Scrapbook\Adapters\SQLite;
use MatthiasMullie\Scrapbook\Psr16\SimpleCache;
use Kodus\Session\Adapters\SimpleCacheAdapter;
use Kodus\Session\SessionMiddleware;

$connection = new PDO('sqlite:cache.db');

$cache = new SimpleCache(new SQLite($connection));

$storage = new SimpleCacheAdapter($cache);

$service = new SessionService($storage);

$middleware = new SessionMiddleware($service);
```

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance87

Actively maintained with recent releases

Popularity36

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~308 days

Recently: every ~679 days

Total

12

Last Release

52d ago

Major Versions

0.2.2 → 1.0.02017-11-29

1.0.0 → 2.0.02018-01-09

2.1.1 → 3.0.02018-10-17

PHP version history (3 changes)0.2.0PHP ^7.0

2.0.0PHP ^7.1

3.1.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/ec1a54f85a6e46909df4ca4852ada0cc4b1482f7208dfc487d05554087e09cc9?d=identicon)[thomasnordahl-dk](/maintainers/thomasnordahl-dk)

![](https://www.gravatar.com/avatar/9d0432f9ee26cc6265bcf3817d88bf40a4a8669a603785b34946e9c15d7b3451?d=identicon)[boan-jfm](/maintainers/boan-jfm)

![](https://www.gravatar.com/avatar/22799a8c3c482e408f78fd86a999b271f1d5fd2e04b433c6d199f717b3032bb2?d=identicon)[JyskFynskeMedierJoej](/maintainers/JyskFynskeMedierJoej)

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

---

Top Contributors

[![thomasnordahl-dk](https://avatars.githubusercontent.com/u/5709900?v=4)](https://github.com/thomasnordahl-dk "thomasnordahl-dk (45 commits)")[![mindplay-dk](https://avatars.githubusercontent.com/u/103348?v=4)](https://github.com/mindplay-dk "mindplay-dk (33 commits)")[![rhl-jfm](https://avatars.githubusercontent.com/u/12860072?v=4)](https://github.com/rhl-jfm "rhl-jfm (8 commits)")[![boan-jfm](https://avatars.githubusercontent.com/u/13201214?v=4)](https://github.com/boan-jfm "boan-jfm (4 commits)")[![hcsagan](https://avatars.githubusercontent.com/u/18111838?v=4)](https://github.com/hcsagan "hcsagan (3 commits)")[![vortrixs](https://avatars.githubusercontent.com/u/15426116?v=4)](https://github.com/vortrixs "vortrixs (3 commits)")

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/kodus-session/health.svg)

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)

PHPackages © 2026

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