Kostas Papastadopoulos Kostas Papastadopoulos - 3 months ago 29x
PHP Question

Symfony 2.8 Global variable

I am using Symfony 2.8 and I didn't find anything to solve my problem.

To make it simple, I have a Payment entity and I need to have a global variable for the VAT.

My question is: is there any way to have a common variable to all my Payment entities knowing it could be modified later within the web application by the administrator? I don't think the Service parameters (which I am using) will make it. At least, I didn't find anything on how to modify it dynamically.

Here's some part of my service.yml:

app_tva: 20


Use real global variable (global $parameter) in Symfony - the vary bad idea, because all systems works in scope (request, console, etc...), and each scope have custom services for this scope (@request as example).

But, if you want use config parameter in you application, then you can use:

Solution #1 (Use app/config/parameters.yml):

This solutions vary good, if parameter is not dynamically, and changed rarely.

  1. Add custom parameter in parameters.yml
  2. Get this parameter from container $container ->getParameter('some_parameter')

Solution #2 (Use a factory service for custom parameters)

In my application, I use custom layer for configurations with common service, because many parameters is dynamically, and can changed for each request or user or another condition.

  1. Create a factory service Acme\DemoBundle\Config\AppConfig as example.
  2. Add method getVat to this service.
  3. Register service in service container.
  4. Inject this service to another service, where you must access to configuration layer.

Solution #3 (Use a Doctrine events)

So, this a not good idea, but can work in any systems.

If you want calculate prices, or another operation with entity, you can inject custom parameter after complete load entity.

Attention: This method work only after load entity via doctrine!

  1. Create a custom listener/subscriber for Doctrine ORM
  2. Inject custom variable to you entity in postLoad event.
  3. Register listener/subscriber as service and add tag doctrine.event_subscriber or doctrine.event_listener


I would use Solution #2, because this is a vary good variant, and we can store this parameter anywhere (database, redis, parameters.yml, etc..), and we can change this parameter for each condition (request, user, country, timezone, etc...)