Building an API part 1.5 - using Symfony dotenv component

Published: 6 years ago php web dev

Okay it's going to be a slight departure from our planned next step on our API because I realised we need to store our database credentials somewhere and it seemed like an ideal opportunity to try out the Symfony dotenv component. This component reads values from a specified config file into environment vars. Using environmental vars helps separate credentials from code and keeps them out of a source control system. But why do you need a component to help with this? Well it's an extra convenience in dev and staging setups. It means theres no need to add any extra config outside your project and it adds improved portability (this method works with Apache, Nginx, PHP web server etc.). You shouldn't be using this component or an .env config file on production systems. Anyway, it's really simple to use, let's set it up.

composer require symfony/dotenv grabs the component so we can load in it.

In our App class we add:

use Symfony\Component\Dotenv\Dotenv; allows us to reference the Dotenv component directly.

In our constructor:

$dotenv = new DotEnv();
$dotenv->load(__DIR__.'/../.env'); //we place the .env file at the API's root

Then all we need to do is create our .env file to test. One thing I tend to do is prefix any environmental variables with my app's name as if (like me) you run multiple virtual hosts, you're going to have problems if multiple websites need different DBUSER values etc.

MYAPP_DBHOST=localhost
MYAPP_DBNAME=blah
MYAPP_DBUSER=blah
MYAPP_DBPASS=blah

After doing this, you can load any environment vars via getenv(), $_SERVER and $_ENV.

How should this work in production? You just assign actual environment variables (source .env) as according to the docs: 'Symfony Dotenv never overwrites existing environment variables'. If you lose the .env file you also need to catch the exception or add additional checks to the above code. Basically as I mentioned earlier, in production you shouldn't be using this component.

A random Symfony aside

Did you know the Symfony coding standards require the use of yoda conditional statements? This is the switching of a condition expression to catch potential accidental assignment errors. It's one of those programmer debates that won't seem to end but I am against such a way of writing conditions. It requires extra mental grokking (especially when you're not use to them) for a small advantage that should be caught in testing anyway.

More info on dotenv

More thinking on dotenv from the original PHP package author here.