symfonyevent-handlingtwigrequestscope

Symfony: How to handle common request scope data


I'm migrating a legacy PHP project (pre-OO) to Symfony2. On every request I have to:

A naive approach would be:

Sounds tedious. Maybe it would be better to:

Is that viable? In particular, are the twig variable/service and the subscriber always identical? Or could the service be a newly created instance?

Is this some sort of misuse? Or is there an officially recommended way for such a use case?

EDIT The data is not only needed in every twig template but in some controllers, too.


Solution

  • Calling a specific method in every Controller-Action would really be a bad solution. Your solution to use a subscriber isn't perfect either.

    Without knowing your use-case in detail it´s hard to find a suitable way. Maybe one approach would be to write a Twig-Extension and injecting a Service into this Extension. The Service would get the Request-Stack via Dependency-Injection and compute the relevant Data. You could then access this data "on demand" through the Twig-Extension during the rendering.
    Another approach could be using sub-requests during the rendering (Symfony: How to handle common request scope data)

    Maybe these tips already helped you a bit. Otherwise let me know more details, where / how you need the data during the rendering.