Change record status: 
Project: 
Introduced in branch: 
8.9.x
Introduced in version: 
8.9.0
Description: 

Developers now can register custom session bags in order to provide type safe interfaces on module specific session data. A session bag must implement the \Symfony\Component\HttpFoundation\Session\SessionBagInterface. Custom session bags are registered using a service entry tagged with the session_bag service tag. Custom session bags can be accessed through the session retrieved from the request object.

Example service definition:

session_test.session_bag:
  class: Drupal\session_test\Session\TestSessionBag
  tags:
    - { name: session_bag }

Example of accessing a custom session bag:

<?php
$bag = $request->getSession()->getBag(TestSessionBag::BAG_NAME);
$bag->setFlag();
?>

Note that Drupal aggressively destroys empty sessions in order to allow for page level caching as much as possible. Thus, it is important for session bag implementations to provide methods for cleaning up obsolete data. I.e., default state must map to the empty session bag. Also client code accessing a custom session bag must be designed such that it cleans up obsolete data from the session bag.

Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done