Using Sessions in Slim 3

Recently, I have seen a few things pop-up around using Sessions within Slim so I'd like to take some time to show how easy it is.

Sessions

There are a few ways to initialize sessions, but by far the simplest is the following.


session_start(); // ¯\_(ツ)_/¯

$app = new Slim\App();


$app->run();

This is equivilant to writing a middleware which also starts the session. Calling session_start in this way will forevery route read the session data for the user. This may/may not be what you want. If you do not want this then you should write a middleware that starts the session. You can then use the middelware and apply it to some routes instead of all.

Example:

$app = new Slim\App();

//The session will start only for routes defined in this group
$app->group(...)->add(function ($req, $res, $next) { 
    session_start();

    //Do not forget to return from the next. 
    return $next($req,$res); 
});

How do I use it?

Well once the session is started then you can use it normally, the session super global will be available.

Gotchas

If you are not applying the sessions to every route be aware of the life-time of the session. Also you will need to be aware of the execution path in your application. If you write a middleware to initialize the session the session will not be initialized when your DI-Container is created that means if you trying to add the contents of the session into TWIG then you should do modify the middleware to add the session after session start.

Written by Glenn Eggleton on Tuesday September 19, 2017
Permalink - Chapter: Slim