thofou76 thofou76 - 1 month ago 8
Twig Question

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:


  • compute some dynamic data (depending on the current date and/or some request parameter)

  • use that data (multiple times!) in the rendered response.



A naive approach would be:


  • At the start of every controller method, call some global helper function to compute the data.

  • At the end of every controller method, pass the data as a parameter to the twig template.



Sounds tedious. Maybe it would be better to:


  • Create a subscriber for request events that computes the data when a request comes in and provides access to it via getter methods.

  • Define that subscriber/service as a global twig variable in
    config.yml
    .

  • In twig templates, call the getter methods on that service as needed.



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.

Answer

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.

Comments