Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 62 ยท Configuration

Configuration and Environments

Learn how Symfony loads config/packages, how dev, prod and test environments differ, how when@env works, what APP_ENV and APP_DEBUG do, and how parameters work.

Almost everything in Symfony is configurable: the framework, Twig, Doctrine, the mailer, the logger. Instead of one giant settings file, Symfony gives each package its own small file and lets you change any value per environment. The same code can then run with debugging and a profiler on your laptop, with aggressive caching in production, and with a throwaway database in tests.

This lesson explains how those files are found and merged, what an environment really is, how to write environment-specific settings with when@, and how parameters let you define a value once and reuse it. Real Symfony config is shown in read-only blocks. The runnable examples are plain-PHP stand-ins that follow the same rules, and each one says what is real and what is simplified.

Where configuration lives

In a standard project the config/ folder looks like this (you saw it in Project Structure):

TEXT
config/
โ”œโ”€โ”€ packages/
โ”‚   โ”œโ”€โ”€ framework.yaml
โ”‚   โ”œโ”€โ”€ twig.yaml
โ”‚   โ”œโ”€โ”€ doctrine.yaml
โ”‚   โ”œโ”€โ”€ dev/
โ”‚   โ”‚   โ””โ”€โ”€ web_profiler.yaml
โ”‚   โ”œโ”€โ”€ prod/
โ”‚   โ”‚   โ””โ”€โ”€ doctrine.yaml
โ”‚   โ””โ”€โ”€ test/
โ”‚       โ””โ”€โ”€ twig.yaml
โ”œโ”€โ”€ routes.yaml
โ”œโ”€โ”€ services.yaml
โ””โ”€โ”€ bundles.php

Each top-level key in a packages/ file is the alias of a bundle or extension: framework:, twig:, doctrine:. The file name does not matter to Symfony (you could put every package in one file), it is just a convention that makes a file easy to find. A typical framework.yaml looks like this:

YAML
# config/packages/framework.yaml
framework:
    secret: '%env(APP_SECRET)%'
    http_method_override: false
    handle_all_throwables: true
    session:
        handler_id: null
        cookie_secure: auto
        cookie_samesite: lax
    php_errors:
        log: true

when@test:
    framework:
        test: true
        session:
            storage_factory_id: session.storage.factory.mock_file

The when@test: block at the bottom is the environment mechanism you will meet in a moment. The kernel loads files in a fixed order, and when two files set the same key, the later one wins (arrays are merged recursively):

flowchart TD
    A["config/packages/*.yaml"] --> B["config/packages/ENV/*.yaml"]
    B --> C["config/services.yaml"]
    C --> D["config/services_ENV.yaml"]
    D --> E["Compiled container in var/cache/ENV/"]

The kernel merges the general files first, then the files of the current environment; later files override earlier ones.

The step that follows is important: Symfony validates every value against the schema each bundle declares, so a typo such as framwork: or an unknown option fails immediately with a clear message instead of being silently ignored. The merged result is then compiled into the container and cached in var/cache/.

Environments: dev, prod, test

An environment is just a name, held in the APP_ENV variable. It does three things:

  1. It selects which config files and when@ blocks are loaded.
  2. It names the cache folder, var/cache/dev/, var/cache/prod/, and so on, so the environments never overwrite each other.
  3. It is passed to the kernel ($kernel->getEnvironment()) and available as the parameter %kernel.environment%.

Symfony ships with three conventional environments:

Environment Used for Typical settings
dev Working on the app Debug on, web profiler, verbose logs, cache rebuilt on change
prod The live site Debug off, errors hidden, fully compiled and cached
test PHPUnit Separate database, mock session, mailer captured, no real e-mail

You can invent more (staging, demo), but you rarely need to. The difference between a staging server and production is almost always values (URLs, keys, hosts), and those belong in environment variables, not in new environments. A staging environment that behaves like prod but with APP_ENV=prod and different variables is simpler to reason about, and it tests the code you will actually ship.

APP_ENV and APP_DEBUG

Two variables control how the kernel boots. You set them in .env, in .env.local, or as real environment variables:

Terminal
APP_ENV=dev
APP_DEBUG=1

APP_ENV picks the environment. APP_DEBUG is a separate switch: it controls whether error pages show stack traces, whether the profiler is available, and whether the cache checks for modified files. In dev it defaults to on and in prod to off. You can mix them for a purpose: APP_ENV=prod APP_DEBUG=1 runs production config with debugging on, which is occasionally useful for reproducing a production-only bug.

The front controller passes both to the kernel, as you read in Project Structure. Never run a public server with APP_DEBUG=1: debug pages leak file paths, config values and sometimes environment variables.

Environment-specific settings

There are two ways to say "only in this environment".

1. A folder named after the environment. Everything in config/packages/prod/ is loaded only when APP_ENV=prod:

YAML
# config/packages/prod/doctrine.yaml
doctrine:
    orm:
        auto_generate_proxy_classes: false
        proxy_dir: '%kernel.build_dir%/doctrine/orm/Proxies'
        query_cache_driver:
            type: pool
            pool: doctrine.system_cache_pool

2. A when@<env> key inside a normal file. It holds an entire set of top-level keys that are merged only in that environment. You can list several environments in the key, separated by commas:

YAML
# config/packages/web_profiler.yaml
when@dev:
    web_profiler:
        toolbar: true
        intercept_redirects: false
    framework:
        profiler: { only_exceptions: false }

when@dev,test:
    monolog:
        handlers:
            main:
                type: stream
                path: '%kernel.logs_dir%/%kernel.environment%.log'
                level: debug

Use whichever reads better. A short tweak for one package fits when@; a package that exists only in development, such as the profiler, usually has its own file that is entirely under when@dev:.

This stand-in loads config the same way: files that apply to every environment first, then the environment's folder, with when@ blocks merged where they appear and recursive overriding. Real Symfony also validates against each bundle's schema, which this stand-in skips.

PHP Layering config files by environment (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Run it and compare the three outputs: only dev has the toolbar, only prod has the Doctrine proxy setting, and test gets framework.test. The shared keys are identical everywhere.

Parameters

A parameter is a named value stored in the container, written once and referenced by name. Define them in config/services.yaml under parameters::

YAML
# config/services.yaml
parameters:
    app.admin_email: '[email protected]'
    app.items_per_page: 20
    app.export_dir: '%kernel.project_dir%/var/exports'
    app.supported_locales: ['en', 'es', 'de']

Three things to know:

  • References use %name%. Inside a string, %kernel.project_dir% is replaced by the project path. If the whole value is one reference, the original type is kept, so %app.items_per_page% stays an integer and %app.supported_locales% stays an array.
  • Literal percent signs are doubled: write 100%% to get 100%.
  • Symfony defines built-ins such as kernel.project_dir, kernel.environment, kernel.debug, kernel.cache_dir, kernel.logs_dir and kernel.charset.

Parameters are resolved when the container is compiled, so they are constants for the whole life of the cached container. That makes them ideal for settings that never change between requests of one deployment. Values that must differ per server or change without rebuilding the cache belong in environment variables, which you will cover in Environment Variables and Secrets.

To get a parameter into your code, inject it. Direct container access is avoided in modern Symfony:

PHP
<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class ReportExporter
{
    public function __construct(
        #[Autowire('%app.export_dir%')]
        private string $exportDir,
        #[Autowire(param: 'app.items_per_page')]
        private int $perPage,
    ) {
    }
}

Controllers can also call $this->getParameter('app.items_per_page'). A third option is ParameterBagInterface, but injecting only what you need keeps classes honest about their dependencies (see Autowiring and Dependency Injection).

The next stand-in resolves %placeholders% the way the container does: whole-value references keep their type, %% is an escape, and unknown or circular references fail with an error.

PHP Resolving parameters (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Inspecting and dumping configuration

You do not need to memorize every option. Symfony can show them:

Terminal
php bin/console config:dump-reference framework      # every option with defaults and comments
php bin/console debug:config framework               # the current resolved config of a package
php bin/console debug:config framework session       # just one branch
php bin/console debug:container --parameters         # all parameters and their values
php bin/console debug:container --env-vars           # environment variables used by the config

config:dump-reference is the best documentation for a package because it always matches the installed version. debug:config shows what the app actually uses after all files and when@ blocks are merged for the current APP_ENV. Add --env=prod to the command to see another environment (for example, php bin/console debug:config framework --env=prod).

After you change config in dev, Symfony rebuilds the cache on the next request because debug mode watches the files. In prod the cache is not checked, so deployments must clear and warm it, which is covered in Performance and Deployment.

When a config value "does nothing", run debug:config for the current environment first. The cause is usually that a when@ block or an environment folder overrides your change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which variable selects the environment (dev, prod, test)?

    APP_ENV names the environment. APP_DEBUG is a separate on/off switch for debug features such as stack traces and the profiler.
  2. 2. You put a setting under when@test: in config/packages/framework.yaml. When is it applied?

    A when@<env> block is merged only for the listed environments. You can list several, separated by commas, such as when@dev,test.
  3. 3. Given the parameter app.items_per_page: 20, what type does %app.items_per_page% have when it is the whole value?

    When the entire value is a single reference, the container returns the parameter as it is. Embedded inside a longer string, it is converted to text.
  4. 4. How do you write a literal percent sign inside a parameter value?

    A doubled %% is the escape for one literal percent sign, so Save 15%% today becomes Save 15% today.
  5. 5. Which command shows the config of a package after all files and when@ blocks are merged?

    debug:config prints the resolved values in use. config:dump-reference prints the available options and defaults, not your values.

Summary

  • Each package has its own file in config/packages/; the top-level key is the package alias, and later files override earlier ones.
  • An environment is a name from APP_ENV that selects config files and the cache folder; APP_DEBUG is a separate switch for debug features.
  • Use config/packages/<env>/ folders or when@env blocks for environment-specific settings; vary values per server with environment variables, not new environments.
  • Parameters are compile-time constants referenced as %name%; whole-value references keep their type and %% is a literal percent sign.
  • Inject parameters with #[Autowire], and explore config with config:dump-reference, debug:config and debug:container --parameters.

Next up: Environment Variables and Secrets.