Generate Optimized File to Store Environment Variables in Symfony 7

Generate Optimized File to Store Environment Variables in Symfony 7

Symfony framework uses .env files for storing environment variables. In all environments (including prod), the .env files are loaded and parsed on each request. This process can be optimized in production environment.

This tutorial shows example how to generate an optimized file to store environment variables in Symfony 7 application.

Let's say we have the following .env file:

.env

APP_ENV=dev
APP_SECRET=3f76486e93328679840de33a51b0a69f

DB_USER=root
DB_PASS=pass

Also, we have the .env.local file which overrides the default values for few variables:

.env.local

DB_USER=admin
DB_PASS=smT9NXrfKZ

To improve performance, we can run the composer dump-env command to generate an optimized .env.local.php file which overrides all other environment variable files (.env, .env.local, etc.).

The command accepts environment name as argument. For example, the following command generates the .env.local.php file for production environment:

composer dump-env prod

The generated file contains all environment variables stored in .env files.

.env.local.php

<?php

// This file was generated by running "composer dump-env prod"

return array (
  'APP_ENV' => 'prod',
  'APP_SECRET' => '3f76486e93328679840de33a51b0a69f',
  'DB_USER' => 'admin',
  'DB_PASS' => 'smT9NXrfKZ',
);

Now Symfony will load the .env.local.php file and will not spend time to parse the .env files.

Leave a Comment

Cancel reply

Your email address will not be published.