Contributed by
Fabien Potencier
in #21234.
A common practice when developing applications is to store some configuration
options as environment variables in a .env
file (pronounced "dot-env"). You
can already use this technique in Symfony applications, but in Symfony 3.3 we've
decided to make it a built-in feature thanks to the new Dotenv component.
In practice, the Dotenv component parses .env
files to make environment
variables stored in them accessible in your application via getenv()
,$_ENV
or $_SERVER
. If your .env
file contains these variables:
1 2 | DB_USER=root
DB_PASS=pass |
The following code will parse them and turn them into environment variables:
1 2 3 | useSymfony\Component\Dotenv\Dotenv;(newDotenv())->load(__DIR__.'/.env'); |
Now you can get the database password in your application as follows:
1 | $dbPassword=getenv('DB_PASS'); |
In addition to loading the variables, you can just parse them because the component defines three stages: load, parse, and populate.
Before creating a new component, we reviewed the existing libraries that provide similar features, but none of them matched our specific set of requirements:
- Variables should not be validated in any way (because the real environment variables can only be strings and you can't validate them).
- The component provides a strict implementation of what you can do in a real
bash shell script and nothing more:
$VAR
and${VAR}
are supported, you can concatenate strings, execute commands and store the result in a variable, etc. - Superb error messages to easily spot any issue.
- Clean and minimal API, without unneeded abstractions like being able to add an
environment variable directly (just use
putenv()
).