I know... stay away from globals.
The thing is I really, really, need to have a value that is accessible and, most important modifiable from different parts of the application. It's a counter for some actions that I need to watch for debug purposes. Googling for anything related to Symfony and globals, always got me to results that suggests using the Container parameters or Twig globals, but the thing is that according to Symfony documentation:
You can only set a parameter before the container is compiled: not at run-time.
The Twig globals are pretty much out of scope given that I need them in controller, not in view.
IMHO, both of these solutions are more like constants than variables.
So, the question is: Is there a best practice to obtain what I need using Symfony or should I just use the PHP globals?
Thank you!
Create a service (e.g: ApplicationGlobals
) with a private property $counter
and public setter and getter to read and write the value. A service class will be instantiated automatically and can be reached from everywhere where you can use the container (get it in the controller or pass it as an argument to other services).
Latter you will be able to add multiple variables, when needed, with their proper getters and setters and use them in your project.
I think you could even write a destructor that stores the new value when Symfony terminates. http://symfony.com/doc/current/service_container.html#creating-configuring-services-in-the-container
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With