Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 3.3 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Define Commands as Services

How to Define Commands as Services

If you’re using the default services.yml configuration, your command classes are already registered as services. Great! This is the recommended setup, but it’s not required. Symfony also looks in the Command/ directory of each bundle and automatically registers those classes as commands.


You can also manually register your command as a service by configuring the service and tagging it with console.command.

In either case, if your class extends Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand, you can access public services via $this->getContainer()->get('SERVICE_ID').

But if your class is registered as a service, you can instead access services by using normal dependency injection.

For example, suppose you want to log something from within your command:

namespace AppBundle\Command;

use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SunshineCommand extends Command
    private $logger;

    public function __construct(LoggerInterface $logger)
        $this->logger = $logger;

        // you *must* call the parent constructor

    protected function configure()
            ->setDescription('Good morning!');

    protected function execute(InputInterface $input, OutputInterface $output)
        $this->logger->info('Waking up the sun');
        // ...

If you’re using the default services.yml configuration, the command class will automatically be registered as a service and passed the $logger argument (thanks to autowiring). In other words, just by creating this class, everything works! You can call the app:sunshine command and start logging.


You do have access to services in configure(). However, try to avoid doing any work (e.g. making database queries), as that code will be run, even if you’re using the console to execute a different command.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.