psr7-sessions/storageless

Functional/immutable approach to session containers

Closed this issue · 3 comments

Currently, the session middleware is designed to inject a mutable session container into the ServerRequestInterface attributes.

While this approach is highly usable, it doesn't really compose well with functional approaches, and it breaks the ServerRequestInterface immutability by design (this choice is conscious).

Here's what the current approach looks like:

function myMiddleware(ServerRequestInterface $request, ResponseInterface $response) : ResponseInterface
{
    $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
    $session->set('counter', $session->get('counter', 0) + 1);

    // .. go on

    return $response;
}

In a functional/immutable world, this would become:

$sessionInjector = new SomeSortOfInjector($cryptoConfig);

function myMiddleware(ServerRequestInterface $request, ResponseInterface $response) use ($sessionInjector) : ResponseInterface
{
    $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
    $session = $session->with('counter', $session->get('counter', 0) + 1);

    // .. go on

    return $sessionInjector->responseWithSession($response, $session);
}

Just a suggestion, but I don't want folks to think "OH EM GEE, THAT LIBRARY BREAKS IMMUTABILITY!"
The mutable approach was consciously picked due to ease of use, but the functional approach is still viable and may be implemented if there is some interest or some strong use-case for it.

OH EM GEE, THAT LIBRARY BREAKS IMMUTABILITY! :trollface:

Seriously, that really breaks message immutability, but while that approach brings some mutability drawbacks, it's not a PSR-7 violation at all, since PSR-7 allows mutable attributes. So I still prefer the "convenient" way in this case.

Yeah, and I also don't want to manually write the session in every middleware anyway :-)

I think this has been discussed enough in #60 too to make it a wontfix