Optional environment variables

Written on Nov 25, 2017

Environment variables are becoming increasingly popular to manage the application configuration. They are one of the main concepts of the twelve-factor app methodology. Their main advantages are that they can be changed between deploys without changing any code and that they don’t need to be checked into the code repository.

Symfony has supported environment variables since day one thanks to the special SYMFONY__ variables. However their behavior was rather simple: when the application container was built, the values of those environment variables were dumped into the compiled container. Therefore, if those variables changed during the application execution, the updated values were ignored.

Sometimes you want to have optional environment variables which can be used at run time and represent these with a default value such as false, empty string or null. Previously, you would have defined default values in app/config/parameters.yml but this file is now absent in Symfony Flex. Instead, you can define them in config/services.yaml:

As a result, the service will now be injected with the default value or the true environment variable if it is set.

Happy development! :wave: