#[Option] in Symfony Console: a command's options

Symfony Console's #[Option] attribute declares a command option as a parameter of __invoke(), typed, with its default value and its help.

#[AsCommand(name: 'app:plat:ajouter', description: 'Adds a dish to the menu.')]
final class AjouterPlatCommand
{
    public function __invoke(
        SymfonyStyle $io,
        #[Argument('The name of the dish')] string $nom,
        #[Argument('Its price, in gold coins')] float $prix,
        #[Option('The category of the dish (by its name)')] string $categorie = '',
        #[Option('It is a house speciality')] bool $specialite = false,
    ): int {
        // app:plat:ajouter "Shire ale" 3.5 --categorie Drinks --specialite
    }
}

In an invokable command, no more configure() or $input->getOption(): the parameter's name gives the option's name ($dryRun gives --dry-run), its type converts the value, and the description passed to the attribute feeds --help. A bool option is switched on without a value; a nullable type, ?string $categorie = null, tells a missing option from an empty one. An option always has a default value, whereas an #[Argument] is expected at a precise position. The trap: thinking an option is mandatory. Nothing forces anyone to type it; it's up to the command to check it's there, and to answer Command::INVALID otherwise.

The exercises have you add to Gorm's inventory a --categorie option that filters the menu, then write Bruna's command: two arguments, a category, an optional description and the --specialite switch.

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

In the tracks

Related concepts

Console commandExit codesCommandTester