How to use Namespaced Sessions in Symfony2
Since Symfony 3, the override of session.attribute_bag.class
parameter doesn't work anymore.
The solution I applied after pulling my hair for a few time is using a compiler pass to override the session.attribute_bag
service class.
I did it in the Kernel directly, but an external compiler pass would work the same way.
SF4 Kernel
<?php
// src/Kernel.php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
// ...
public function process(ContainerBuilder $container)
{
$container->getDefinition('session.attribute_bag')->setClass(NamespacedAttributeBag::class);
}
}
Just open your config.yml and after imports add:
parameters:
session.attribute_bag.class: Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag
It looks like this:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
parameters:
session.attribute_bag.class: Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag
framework:
# ...
Because it's also possible to use the HTTPFoundation Component outside of Symfony2, the way to implement NamespacedUserBags is as follows:
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
$session = new Session();
//first bag
$myAttributeBag = new NamespacedAttributeBag('<your_storage_key_1>');
$myAttributeBag->setName('<your_tag_name_1>');
$session->registerBag($myAttributeBag);
//second bag
$myAttributeBag = new NamespacedAttributeBag('<your_storage_key_2>');
$myAttributeBag->setName('<your_tag_name_2>');
$session->registerBag($myAttributeBag);
$session->start();
Register as many bags as you want, but make sure to do this before you start the session. Now you can switch between bags using getBag():
$activeBag = $session->getBag('<your_tag_name>');
and access the namespaced bag with the typical methods :
$activeBag->set('tokens/a', 'adsf82983asd');
$activeBag->set('tokens/b', 'daslfl232l3k');
print_r($activeBag->get('tokens'));
You should redefine session service and also define service for your attribute bag (if you'll check default implementation of session.attribute_bag
you'll see that this service has only class attribute).
And inject your new service to redefined session service into there
services:
session:
class: Symfony\Component\HttpFoundation\Session\Session
arguments:
- @session.storage
- @your.session.attribute_bag #service id is defined below
- @session.flash_bag
your.session.attribute_bag:
class: Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag