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.