2 Methods to Define Console Command Lazy Loaded in Symfony 7

2 Methods to Define Console Command Lazy Loaded in Symfony 7

In Symfony application, console commands can be lazy loaded. It means that the command is instantiated when it is actually called. It can improve performance you have lots of commands which uses many services.

This tutorial provides 2 methods how to define console command lazy loaded in Symfony 7 application.

Method 1 - 'AsCommand' attribute

We can make console command lazy loaded by specifying command name with the AsCommand attribute.

src/Command/TestCommand.php

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        return Command::SUCCESS;
    }
}

Method 2 - 'command' attribute

Console command can be defined lazy loaded by adding the command attribute to the console.command tag in the service definition.

config/services.yaml

services:
    # ...

    App\Command\TestCommand:
        tags:
            - { name: 'console.command', command: 'app:test' }

src/Command/TestCommand.php

<?php

namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TestCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        return Command::SUCCESS;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.