Symfony News

New in Symfony 4.1: Session improvements

Deprecate some uses of Request::getSession()

Contributed by
Florent Mata
in #26564.

Using Request::getSession() when no session exists has been deprecated in Symfony 4.1 and it will throw an exception in Symfony 5.0. The solution is to always check first if a session exists with the Request::hasSession() method:

1
2
3
4
// ...
if ($request->hasSession() && ($session = $request->getSession)) {
    $session->set('some_key', 'some_value');
}

Allow to cache requests that use sessions

Contributed by
Yanick Witschi
in #26681.

Whenever the session is started during a request, Symfony turns the response into a private non-cacheable response to prevent leaking private information. However, even requests making use of the session can be cached under some circumstances.

For example, information related to some user group could be cached for all the users belonging to that group. Handling these advanced caching scenarios is out of the scope of Symfony, but they can be solved with the FOSHttpCacheBundle.

In order to disable the default Symfony behavior that makes requests using the session uncacheable, in Symfony 4.1 we added the NO_AUTO_CACHE_CONTROL_HEADER header that you can add to responses:

1
2
3
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;

$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');

Allow to migrate sessions

Contributed by
Ross Motley
in #26096.

Migrating sessions (e.g. from the filesystem to the database) is a tricky operation that usually ends up losing all the existing sessions. That's why in Symfony 4.1 we've introduced a new MigratingSessionHandler class to allow migrate between old and new save handlers without losing session data.

It's recommended to do the migration in three steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MigratingSessionHandler;

$oldSessionStorage = ...;
$newSessionStorage = ...;

// The constructor of the migrating class are: MigratingSessionHandler($currentHandler, $writeOnlyHandler)
// Step 1. Do this during the "garbage collection period of time" to get all sessions in the new storage
$sessionStorage = new MigratingSessionHandler($oldSessionStorage, $newSessionStorage);

// Step 2. Do this while you verify that the new storage handler works as expected
$sessionStorage = new MigratingSessionHandler($newSessionStorage, $oldSessionStorage);

// Step 3. Your app is now ready to switch to the new storage handler
$sessionStorage = $newSessionStorage;

Be trained by Symfony experts - 2018-04-26 Paris - 2018-05-14 Cologne - 2018-05-14 Paris


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook