I am trying to tidy up my session variables by integrating custom AttributBags into the session. In Symfony < 6.0 you were able to inject a custom AttributBag into the session service.

See related questions

* [How to add extra bag to symfony session](https://stackoverflow.com/questions/44723613/how-to-add-extra-bag-to-symfony-session)
* [Using Symfony AttributeBags in a Controller](https://stackoverflow.com/questions/44727632/using-symfony-attributebags-in-a-controller)

However this approach does not work anymore in Symfony >= 6.0. This [blog article](https://symfony.com/blog/new-in-symfony-5-3-session-service-deprecation) explains that the session service is deprecated and must now be accessed over the request\_stack service. For controllers this works fine.

My current (not working) approach looks like this: Define a custom AttributBag class.

```php
class ShoppingCartBag extends AttributeBag {
    public function __construct(string $storageKey = 'shoppingCart') {
        parent::__construct($storageKey);
    }
}

```

Add a custom CompilerPass in the Kernel class so that Symfony takes care of all changes while building the container.

```php
class Kernel extends BaseKernel {
    use MicroKernelTrait;

    protected function build(ContainerBuilder $container): void {
        $container->addCompilerPass(new AddShoppingCartBagToSessionService());
    }
}

```

The custom CompilerPass looks like this.

```php
class AddShoppingCartBagToSessionService implements CompilerPassInterface {

    public function process(ContainerBuilder $container) {
        $container->getDefinition('request_stack') //<- Works, but how to access the session?
            ->addMethodCall('getSession') // How to bridge the gap? This thought does not work. I assume it is because the session is not yet instantiated when the container is build.
            ->addMethodCall('registerBag', [new Reference('App\Session\CustomBag\ShoppingCartBag')]);
    }
}

```