Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Console
  4. How to Define Commands as Services
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
  • Lazy Loading

How to Define Commands as Services

Edit this page

Warning: You are browsing the documentation for Symfony 3.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.3 (the current stable version).

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.

Symfony also looks in the Command/ directory of each bundle for commands non registered as a service and automatically registers those classes as commands. However, this auto-registration was deprecated in Symfony 3.4. In Symfony 4.0, commands won't be auto-registered anymore.

Note

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 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
{
    protected static $defaultName = 'app:sunshine';
    private $logger;

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

        // you *must* call the parent constructor
        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->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.

Caution

You do have access to services in configure(). However, if your command is not lazy, 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.

Lazy Loading

3.4

Support for command lazy loading was introduced in Symfony 3.4.

To make your command lazily loaded, either define its $defaultName static property:

1
2
3
4
5
6
class SunshineCommand extends Command
{
    protected static $defaultName = 'app:sunshine';

    // ...
}

Or set the command attribute on the console.command tag in your service definition:

1
2
3
4
5
6
services:
    # ...

    AppBundle\Command\SunshineCommand:
        tags:
            - { name: 'console.command', command: 'app:sunshine' }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <!-- ... -->

        <service id="AppBundle\Command\SunshineCommand">
            <tag name="console.command" command="app:sunshine"/>
        </service>

    </services>
</container>
1
2
3
4
5
6
7
use AppBundle\Command\SunshineCommand;

// ...

$container->register(SunshineCommand::class)
    ->addTag('console.command', ['command' => 'app:sunshine'])
;

Note

If the command defines aliases (using the getAliases() method) you must add one console.command tag per alias.

That's it. One way or another, the SunshineCommand will be instantiated only when the app:sunshine command is actually called.

Note

You don't need to call setName() for configuring the command when it is lazy.

Caution

Calling the list command will instantiate all commands, including lazy commands.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Code consumes server resources. Blackfire tells you how

    Code consumes server resources. Blackfire tells you how

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of buffcode, a Symfony contributor

    Thanks buffcode for being a Symfony contributor

    2 commits • 28 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Meilisearch