Symfony console command: writing a command with #[AsCommand]

A Symfony console command is a class marked #[AsCommand] whose __invoke() method does the work, run by bin/console or by a script.

#[AsCommand(name: 'app:inventaire', description: 'Shows the menu inventory.')]
final class InventaireCommand
{
    public function __construct(private readonly CategorieRepository $categories)
    {
    }

    public function __invoke(SymfonyStyle $io, #[Option('Only show one category')] ?string $categorie = null): int
    {
        $io->title('Menu inventory');
        // …
        if ([] === $categories) {
            $io->error(sprintf('The category "%s" does not exist.', $categorie));

            return Command::FAILURE;
        }
        // …
        return Command::SUCCESS;
    }
}

Like any service, the command receives its dependencies through the constructor; its arguments and options are declared directly in __invoke(), with #[Argument] and #[Option]. SymfonyStyle gives a consistent output: title(), table(), success(), error(). The exit code, Command::SUCCESS, FAILURE or INVALID, is all that a script, a scheduled task or the CI remembers. The trap: with --no-interaction, nobody is there to answer, and $io->confirm() takes its default value. A confirmation that defaults to false means a nightly script no longer saves anything, without a single error.

The exercises have you run the command that loads the menu into the database, write app:inventaire, a table filterable by category that fails on an unknown category, fix commands that mislead scripts with their exit code or their confirmation, then write app:soirees:rappeler, which sends a reminder the evening before to the people registered for the next day's evenings, never sending twice, with a --dry-run option.

4 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

Exit codesDependency injection#[Option]CommandTesterDebuggingBatch processingMailerMigrations