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 | use Symfony\Component\Dotenv\Dotenv;
(new Dotenv())->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:
$VARand${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()).


Comments
`$kernel = new AppKernel(getenv('SYMFONY_ENV') ?: 'prod', getenv('SYMFONY_DEBUG') ?: false);`
Will they work seamlessly together ? Or will there will be some conflict if I have variable "ABC" defined both as environment variable AND in the ".env" file ?
Thanks.
You wrote "You can already use this technique in Symfony applications", but I haven't found anything about the possibility to use a .env file in the official documentation or blog.