'Using Symfony NamespacedAttributeBags in a Controller

It's my first time using NamespacedAttributeBag so I try the following code but it gives me an exception "The SessionBagInterface TestData is not registered." when I call it from another location, also inside the same controller.

Controller:

public function indexAction(Request $request, SessionInterface $session)
{
    $session = $request->getSession();

    $bag = new NamespacedAttributeBag();
    $bag->setName('TestData');
    $bag->set("Type", "Dummy");

    $session->registerBag($bag);
}

public function getDataAction(Request $request, SessionInterface $session)
{
    $session = $request->getSession();
    $bag = $session->getBag('TestData');
}

What I want to archive is to define a bag with a couple of attributes (arrays) and use this bag on another function or controller.

The expeption says that the bag is not defined and I can see it is true when I dump the session (dump($session)) inside getDataAction. I can see only two default bags attributes and flashes but is missing TestData.

I searched for a more complete example of this but I did not find anything very useful. I don't have it very clear if this can't be used as I want or I'm missing something important.



Solution 1:[1]

On Symfony 4.2,

In order to use the NamespacedAttributeBag project-wise, you can override the "session.attribute_bag" service in the config/services.yaml :

services:
    _defaults:
        autowire: true      
        autoconfigure: true  
 ...
    'session.attribute_bag':
         class: 'Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag'

and now use your namespacing for the user's session data from the controller without any other configuration :

class DossierController extends AbstractController {
    public function index(Request $request) {
       $request->getSession()->set('namespace1/categoryA/value1', $value);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicolas Martin