Advertisement
Intermediate PHP, Symfony Framework Essentials

What is Symfony's service container, and how does dependency injection work within a typical Symfony application?

Short answer

Symfony's service container is responsible for creating and managing the various service objects an application depends on, such as a database connection, a mailer, or a custom business logic class, and rather than a controller or service manually creating its own dependencies…

Save PHP mock interview
Advertisement
AModel answer
Symfony's service container is responsible for creating and managing the various service objects an application depends on, such as a database connection, a mailer, or a custom business logic class, and rather than a controller or service manually creating its own dependencies, Symfony's container automatically injects the required dependencies wherever they are needed, typically by simply type hinting the required dependency as a constructor parameter, letting the container figure out how to construct and provide the correct instance automatically.
class OrderService
{
    public function __construct(
        private MailerInterface $mailer,
        private LoggerInterface $logger,
    ) {}
}
Real-world example
A Symfony application defines an OrderService that simply type hints a mailer and a logger in its constructor, and Symfony's service container automatically provides fully configured instances of both whenever that service is actually needed, without any manual wiring required.
Likely follow-ups
  • What is autowiring, and how does it relate to the service container?
  • How would you configure a service that needs a specific, non default value passed to its constructor?
Related topics