Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 62 ยท Services and the Container

Configuring Services

Configure Symfony services with _defaults, resource loading, bind, arguments, parameters, environment variables and autoconfigure, with a runnable parameter resolver.

Autowiring covers objects, but services also need plain values: a VAT rate, an API key, a directory, a feature flag. Symfony offers several ways to supply them, and picking the right one keeps your configuration short and your classes easy to test.

This lesson walks through services.yaml in detail: _defaults, loading classes in bulk, arguments, bind, container parameters, environment variables and autoconfigure. All real configuration is shown read-only. A stand-in resolver then shows how %parameters% and %env(...)% placeholders become values, using the same naming and replacement rules in miniature.

The anatomy of services.yaml

YAML
# config/services.yaml
parameters:
    app.vat_rate: 0.2
    app.invoice_dir: '%kernel.project_dir%/var/invoices'

services:
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            string $invoiceDir: '%app.invoice_dir%'

    App\:
        resource: '../src/'
        exclude:
            - '../src/Entity/'
            - '../src/Kernel.php'

    App\Service\PriceCalculator:
        arguments:
            $vatRate: '%app.vat_rate%'

There are three blocks: parameters (named values), _defaults (settings applied to every service defined in this file after it) and services (definitions). The sections below take them in turn.

_defaults

_defaults sets options once instead of repeating them for each service. The two you will always see are autowire: true and autoconfigure: true. You can add public: false (already the default) and bind values. A service can override a default with its own entry, for example autowire: false.

Loading classes in bulk

The App\: entry with resource is a prototype: for every class found under the path, Symfony registers a service whose id is the fully qualified class name. exclude removes directories and files that are not services. If your namespace is deeper, you can add a second prototype:

YAML
    App\Legacy\:
        resource: '../src/Legacy/'
        autowire: false

Registering a class twice (once through the prototype and once by name) is not a problem: the explicit definition later in the file overrides the generated one, which is why the PriceCalculator entry above can add arguments.

Passing values

arguments

arguments fills constructor parameters. Prefer named arguments ($vatRate) over a positional list, because they survive a changed parameter order. Autowiring still handles every parameter you do not mention.

bind

bind assigns a value to every service parameter with a given name (and optionally type) at once. It is ideal for values used in many places:

YAML
services:
    _defaults:
        bind:
            string $adminEmail: '[email protected]'
            $projectDir: '%kernel.project_dir%'

A service that declares string $adminEmail anywhere in its constructor, or in a controller action, now receives that value. Symfony reports an error if a bind is never used, which helps catch typos.

#[Autowire] in code

If you prefer to keep the choice in the class, the #[Autowire] attribute does the same without YAML:

PHP
<?php
namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class InvoiceWriter
{
    public function __construct(
        #[Autowire('%kernel.project_dir%/var/invoices')]
        private string $directory,
        #[Autowire(param: 'app.vat_rate')]
        private float $vatRate,
        #[Autowire(env: 'MAILER_FROM')]
        private string $from,
        #[Autowire(service: 'app.special_logger')]
        private LoggerInterface $logger,
    ) {
    }
}

param: reads a container parameter, env: reads an environment variable, service: picks a service by id, and a plain string may contain %parameters% and %env()% placeholders. Use the attribute for one-off values and bind for values shared across the project.

Parameters

A parameter is a named, scalar-or-array value stored in the container. Names conventionally start with your own prefix (app.), because Symfony and bundles use their own namespaces such as kernel. and framework.. Reference one with percent signs: '%app.vat_rate%'. Quote the string, because % has a meaning in YAML. To write a literal percent sign, double it: '100%%'.

Parameters are resolved when the container is compiled, so they are constants for the lifetime of a deployment. Useful built-ins are %kernel.project_dir%, %kernel.environment% and %kernel.debug%. List all of them with php bin/console debug:container --parameters.

Environment variables

Values that differ per machine or contain secrets belong in environment variables. In configuration, write %env(NAME)%:

YAML
parameters:
    env(MAILER_FROM): '[email protected]'   # default if the variable is not set

services:
    App\Service\InvoiceWriter:
        arguments:
            $from: '%env(MAILER_FROM)%'
            $limit: '%env(int:INVOICE_LIMIT)%'

The part before the colon is an env var processor: int, float, bool, json, csv, file, trim, base64, resolve and more. They convert the string the operating system provides into the type you need. Unlike parameters, environment variables are read at runtime (on first use), so changing one does not require rebuilding the container. Environment variables and secrets covers .env files and the secrets vault.

PHP Resolving %parameters% and %env()% (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.

The output shows the three rules you will meet daily: parameters are looked up by name, an env(NAME) parameter is the default used when the variable is not set, and a missing name is an error, not an empty string.

autoconfigure

autoconfigure: true means: look at what a class is, and tag it accordingly. If your class implements EventSubscriberInterface, extends Command, or implements ConstraintValidatorInterface, Symfony adds the right tag so the framework finds it. Attributes such as #[AsCommand], #[AsEventListener] or #[AsMessageHandler] work the same way. Without autoconfigure you would have to write a tags: entry for every one of these classes.

PHP
<?php
namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;

#[AsCommand(name: 'app:send-invoices', description: 'Sends pending invoices.')]
final class SendInvoicesCommand extends Command
{
}

That class needs no entry in services.yaml: the prototype registers it, autoconfigure tags it as a console command and bin/console list shows it. Read about explicit tags in Tags, Decorators and Service Locators.

flowchart LR
    F["services.yaml<br/>_defaults + resource"] --> D["Service definitions<br/>one per class"]
    P["parameters and env vars"] --> D
    A["autoconfigure<br/>adds tags from interfaces and attributes"] --> D
    D --> C["Compiled container<br/>var/cache"]

Configuration is merged into service definitions, which are compiled once into PHP code.

Which tool for which value?

  • Same value in many services (project directory, admin email): bind in _defaults.
  • One service, one value: arguments, or #[Autowire] in the class.
  • A value that never changes between machines (VAT rate, page size): a parameter.
  • A value that differs per environment or is secret (API key, database password): an environment variable, ideally read through #[Autowire(env: ...)].

Avoid reading $_ENV or getenv() in your classes: config belongs to the container, and your classes should just receive values through their constructor.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does bind: { string $adminEmail: '...' } under _defaults do?

    bind matches arguments by name (and type) across all services that share the defaults, so you set a shared value once.
  2. 2. How do you write a literal percent sign in a YAML parameter value?

    A percent sign starts a parameter placeholder, so a literal one is doubled.
  3. 3. What is a key difference between a parameter and an environment variable?

    Parameters are compiled into the container. Environment variables are looked up when first used, so they can change without a rebuild.
  4. 4. What does autoconfigure: true do for a class that implements EventSubscriberInterface?

    Autoconfigure reads interfaces, base classes and attributes and tags the service accordingly, so no tags entry is needed.

Summary

  • services.yaml has parameters, _defaults and services; a resource prototype registers every class in a directory.
  • Pass values with arguments, shared bind entries or #[Autowire] (param:, env:, service:).
  • Parameters use %name% and are fixed at compile time; environment variables use %env(processor:NAME)% and are read at runtime.
  • autoconfigure adds tags from interfaces and attributes so most classes need no manual configuration.
  • Keep configuration in the container and give classes plain constructor arguments.

Next, use tags to let services find each other in Tags, Decorators and Service Locators.