Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 62 ยท Services and the Container

Services and the Service Container

Learn what a Symfony service is, how the service container creates and shares objects, how services.yaml registers them, and how to inspect them with debug:container.

Almost everything useful in a Symfony application is an object that does one job: send an email, calculate a price, talk to a database, render a template. Symfony calls such an object a service. Instead of creating services with new all over your code, you ask a central object, the service container, to build them for you and hand them out wherever they are needed.

This lesson explains what services are, what the container does, how a service gets registered in config/services.yaml, and which console commands show you what is inside. The real container is generated PHP code that runs inside Symfony, so real code is shown read-only. A small container stand-in below lets you watch the main behavior yourself: lazy creation and sharing one instance.

What is a service?

A service is any object that your application uses to get work done, as opposed to an object that merely holds data. A PriceCalculator is a service. An Order that stores items and a total is a data object (often called an entity or a DTO) and is usually not a service.

PHP
<?php
namespace App\Service;

final class PriceCalculator
{
    public function __construct(private float $vatRate = 0.2) {}

    public function withVat(float $net): float
    {
        return round($net * (1 + $this->vatRate), 2);
    }
}

Services tend to be stateless and configured through the constructor. They collaborate: a CheckoutService needs a PriceCalculator and a Mailer. If each class built its own collaborators, you could not replace them in tests, share one database connection, or change a setting in one place. The container solves that. See Dependency injection for the underlying idea in plain PHP.

What the container does

The service container is a registry that knows how to build each service and keeps the instances it has built.

  1. You ask for a service by its identifier (in Symfony, usually its class name).
  2. If the container has already built it, it returns the same instance.
  3. If not, it builds it: it reads the constructor, builds every dependency first, creates the object and stores it.

Two properties matter. Services are lazy: nothing is built until something asks for it, so a request that never sends email never creates the mailer. And services are shared by default: every consumer receives the same instance, so there is one database connection per request, not one per class.

flowchart TD
    C["Controller asks for CheckoutService"] --> K["Container"]
    K -->|"not built yet"| B["Build dependencies first"]
    B --> P["PriceCalculator"]
    B --> M["Mailer"]
    P --> R["Create CheckoutService"]
    M --> R
    R --> S["Store instance, return it"]
    S -->|"next request for the same service"| K

The container builds dependencies first, caches the new instance, and hands out the same one afterwards.

PHP A tiny service container (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 laziness (no object exists until the first get()), dependency order (the calculator and mailer are built before the checkout service) and sharing (the second call builds nothing). The error message imitates Symfony's own wording for an unknown service.

Registering services: services.yaml

In a Symfony application you rarely call a container method yourself. You describe services in config/services.yaml, and Symfony turns the description into optimized PHP code. A fresh project contains this:

YAML
# config/services.yaml
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # inject dependencies by type-hint
        autoconfigure: true # register commands, listeners, ... automatically

    # make every class in src/ available as a service
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'

Those few lines register every class in src/ as a service whose identifier is its fully qualified class name. Entities are excluded because they are data objects. With this file, a new class App\Service\PriceCalculator is immediately a service: no registration code, no per-class entry. The next lessons explain each part: autowiring, then _defaults, bind and parameters.

You can still define a service by hand when it needs special arguments:

YAML
services:
    App\Service\PriceCalculator:
        arguments:
            $vatRate: 0.19

Getting a service

Symfony prefers dependency injection: declare what you need in a constructor (or a controller action) and the container supplies it.

PHP
<?php
namespace App\Controller;

use App\Service\PriceCalculator;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class PriceController
{
    #[Route('/price/{net}')]
    public function show(float $net, PriceCalculator $calculator): Response
    {
        return new Response((string) $calculator->withVat($net));
    }
}

You do not call $container->get() in application code. Fetching services from the container directly hides a class's real dependencies, makes tests harder and fights Symfony's optimizations. The container is meant to work behind the scenes.

In Symfony 4 and later, services are private by default. They can be injected, but you cannot fetch them by calling get() on the container from outside. This was a deliberate choice that lets Symfony inline or remove unused services when it compiles the container.

Looking inside: console tools

Because the container is configuration, you need a way to inspect it. These commands are the most useful:

Terminal
php bin/console debug:container                       # list public-facing services
php bin/console debug:container --show-hidden         # include internal ones
php bin/console debug:container App\\Service\\PriceCalculator
php bin/console debug:container --parameters          # container parameters
php bin/console debug:container --tag=kernel.event_listener
php bin/console debug:autowiring mailer               # types you can type-hint
php bin/console lint:container                        # check that wiring is valid

debug:container with a class name prints the service's class, tags, whether it is shared, public, autowired and lazy, and its arguments. debug:autowiring answers "what can I type-hint?", and lint:container catches mistakes such as an argument of the wrong type before they reach production.

The compiled container lives in var/cache/<env>/. You never edit it, and when you change service configuration in development, Symfony rebuilds it automatically. In production you rebuild it with cache:clear or cache:warmup during deployment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is most likely a service?

    A service is an object that performs work. Objects that mainly hold data, such as an Order, are normally not services.
  2. 2. What does it mean that services are shared by default?

    The container stores the instance it built and returns it again, so one database connection or one mailer is reused within a request.
  3. 3. Why are services built lazily?

    Laziness avoids paying for objects a request never uses, such as a mailer on a page that sends no mail.
  4. 4. Which command tells you which type-hints you can use for autowiring?

    debug:autowiring lists the autowirable classes and interfaces. debug:container shows the registered services themselves.

Summary

  • A service is an object that does work; the service container builds services, wires their dependencies and keeps the instances.
  • Services are lazy and shared by default, and private by default since Symfony 4.
  • config/services.yaml with a resource entry registers every class in src/ as a service named after its class.
  • Ask for services with constructor or action arguments; avoid calling get() on the container.
  • debug:container, debug:autowiring and lint:container let you inspect and verify the wiring.

Next, see how Symfony fills those constructor arguments for you in Autowiring and Dependency Injection.