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.