Symfony environments
In Symfony, the idea of “environments” is the idea that the same codebase can behave differently (by using different configurations).
We have one application, but we need to behave differently at different times:
- when developing, we need to log everything and debug
- on production, we need optimization for speed and only log errors
A Symfony environment is a set of configuration.
Configuration environments
We can change the application behavior by changing which configuration files are loaded.
Symfony loads the configuration files in this order
(the last files can override the values set in the previous ones):
config/packages/*.yaml
- general/shared configuration*config/packages/<environment-name>/*.yaml
- configs for specific envconfig/services.yaml
config/services_<environment-name>.yaml
*All environments share a large base of common configuration, which is put in files directly in the config/packages/
directory.
For actual implementation you can check \App\Kernel::configureContainer()
method: https://github.com/symfony/symfony/blob/6.1/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php#L49
Pre-defined environments
A typical Symfony application begins with three environments:
- dev (for local development ),
- test (for automated tests) and
- prod (for production servers ).
Select active environment
To select the environment, only change the APP_ENV
environment variable.
This APP_ENV
is passed to the kernel:
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
This value is used both for the web and for the console commands.
We can override it for commands by setting the --env=<environment-name>
Debug mode
Important, but unrelated to the topic of environments is the second argument to the Kernel
constructor. This specifies if the application should run in "debug mode".
This affects many things in the application, such as displaying stacktraces on error pages or if cache files are dynamically rebuilt on each request.
Creating a New Environment
- Create a configuration directory with the same name as the environment in
config/packages/<environment-name>
- Add the needed configuration files in this folder to define the behavior of the new environment Note: you can specify only the differences from shared configuration (
config/packages/*.yaml
) - Select the environment using the
APP_ENV
env var
We can import configuration from different environment using a special imports
key. E.g.
# config/packages/<environment-name>/other.yaml
imports:
- { resource: '../prod/' }
OR we can create symbolic links to create similar environments (to reuse the same configuration).