Git Product home page Git Product logo

session-middleware's Introduction

Session middleware

Build Status Scrutinizer Code Quality Code Coverage Packagist Stable Version Packagist License

Using superglobals like $_SESSION object makes it difficult to test an application as global variables can have unexpected side effects. Using superglobals undermines the effort of using dependency injection and using containers.

The middleware creates an object that wraps $_SESSION, which is available for dependency injection and as attribute of the PSR-7 ServerRequest. The middleware complies with PSR-15. It will also work as double pass middleware.

Installation

composer require jasny/session-middleware

Usage

use Jasny\Session\SessionMiddleware;

$router->add(new SessionMiddleware());
$response = $router->handle($request);

Get the session object from the PSR-7 ServerRequest object and use it as array

$session = $request->getAttribute('session');
$session['foo.bar'] = 10;

if (isset($session['foo.user'])) {
  // ...
}

The session is started by the middleware.

Methods

The session object implements SessionInterface and has the following methods;

  • start() - Start the session.
  • status() - Get the session status.
  • stop() - Write session data and end session.
  • abort() - Discard session array changes and finish session.
  • clear() - Clear all data from the session.
  • kill() - Destroy the session and remove the session cookie.
  • rotate() - Delete the current session and start a new one.

When rotating a session, it's possible to copy some of the data by supplying a callback.

$session->rotate(fn(array $oldSessionData) => ['tid' => $oldSessionData['tid'] ?? null]);

Session options

By default, the middleware will create a GlobalSession object. This object is linked to PHPs session management including $_SESSION. You can manually instantiate this object, supplying session options. These options are passed to session_start().

use Jasny\Session\GlobalSession;
use Jasny\Session\SessionMiddleware;

$session = new GlobalSession([
    'cookie_lifetime' => 0,
    'cookie_httponly' => 1,
    'use_only_cookies' => 1,
    'use_trans_sid' => 0,
    'cookie_secure' => (bool)($_SERVER['HTTPS'] ?? false),
    'cookie_samesite' => 'Lax',
]);

$router->add(new SessionMiddleware($session));
$response = $router->handle($request);

Flash

The session flash object can be used to pass a message to the next request. It is automatically removed from the session after it is used. A typical use case is to store information in a database, than redirect to a page and showing a success message. Or if the information could not be saved, to show an error message.

The flash information contains a type (e.g. success, error, info, warning) and a message. Optionally a content type can be specified for the message. This defaults to text/plain.

$session->flash('success', 'The information has been saved');

In the next request

{% for flash in app.flashes() %}
    <div class="flash-{{ flash.type }}">
        {{ flash.message }}
    </div>
{% endfor %}

If flash() or flashes() is called, the flash messages are cleared from the session. To prevent this call reissue()

$session->flashes()
    ->reissue()
    ->add('warning', "Could not display the page");

header('Location: /other-page');
exit();

Call $session->flashes()->clear() to explicly clear all flash messages, both newly added (to the session) and those available for the current request.

Testing

When running tests, you can injecting a MockSession object in the server request before passing it to the middleware.

use Jasny\Session\MockSession;

$session = new MockSession([
  'foo.user' => '[email protected]'
]);

$requestWithSession = $request->withAttribute('session', $session);
$response = $router->handle($requestWithSession);

Alternatively you can pass a session object when creating the SessionMiddleware. This session object will be used instead of the global session.

use Jasny\Session\SessionMiddleware;
use Jasny\Session\MockSession;

$mockSession = new MockSession();

$router->add(new SessionMiddleware($mockSession));
$response = $router->handle($request);

session-middleware's People

Contributors

jasny avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

ncou m0003r

session-middleware's Issues

Make code PHP 8.1 compatible

When using the library with PHP 8.1, I'm getting a deprecation error for the ArrayAccess implementations of GlobalSession:

Return type of Jasny\Session\GlobalSession::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/gbirke/src/mealplan/vendor/jasny/session-middleware/src/GlobalSession.php on line 149

Depending on how compatible you want this library to be, you could either add a mixed return type (min. PHP version 8.0) or a #[\ReturnTypeWillChange] (backwards compatible for PHP 7.x) to the methods of the ArrayAccess implementation. The MockSession is probably affected too

jasny/php-code-quality dependency

Hi there, I noticed that the jasny/php-code-quality dependency is in composer's require section, not require-dev. Is that intended? It pulls in some seemingly unneeded packages into projects that use session-middleware, and there's an increased chance of version conflicts.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.