Setting default environment variables in Symfony 4

Tom Newby
1 min readJan 16, 2018

--

Photo by Blake Connally on Unsplash

From version 3.2 onwards, Symfony began truly supporting environment variables. This is a huge boon for engineering simple, repeatable deploy processes without having shared parameter.yml files on the server and is the third tenant of the Twelve-Factor App: store config in the environment.

When designing your system, you may wish to have some optional environment variables, such as if you’re building integrations which can be enabled/disabled 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 Symfony4. Instead, you can define it similarly in config/services.yaml:

# config/services.yamlparameters:    ...

# Setting the default value as an empty string, in case it is absent from the server
env(INTERCOM_ACCESS_TOKEN): ''

services:
... # Example service utilising this environment variable App\Service\IntercomService:
class:
App\Service\IntercomService
arguments:
- "%env(INTERCOM_ACCESS_TOKEN)%"

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

--

--