Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 62 ยท Events, Messaging and Console

Console Commands

Write your own bin/console commands in Symfony: #[AsCommand], arguments and options, SymfonyStyle tables and progress bars, exit codes and testing, with a runnable stand-in.

Every Symfony project ships with bin/console, a command-line tool that creates controllers, clears the cache, runs migrations and starts Messenger workers. The same machinery is open to you. Writing your own command is the right choice for anything that runs outside a web request: importing a CSV, cleaning old records, sending a nightly digest, or a one-off data fix that you want to be repeatable.

This lesson shows the real Console component (read-only here) and then rebuilds its core ideas in plain PHP so you can run them: parsing arguments and options, writing output, exit codes, tables, progress bars and a test harness. If you want the theory behind the container injection used below, see autowiring; for running commands on a timer see Scheduler and Lock.

Anatomy of a command

A command is a class registered with the #[AsCommand] attribute. It extends Command, describes its input in configure() and does its work in execute().

PHP
// src/Command/GreetCommand.php (real Symfony, read-only)
namespace App\Command;

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

#[AsCommand(name: 'app:greet', description: 'Greets someone')]
final class GreetCommand extends Command
{
    protected function configure(): void
    {
        $this
            ->addArgument('name', InputArgument::REQUIRED, 'Who to greet')
            ->addOption('yell', 'y', InputOption::VALUE_NONE, 'Use capital letters')
            ->addOption('times', null, InputOption::VALUE_REQUIRED, 'How many times', 1);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $text = 'Hello, ' . $input->getArgument('name') . '!';
        if ($input->getOption('yell')) {
            $text = strtoupper($text);
        }

        for ($i = 0; $i < (int) $input->getOption('times'); $i++) {
            $output->writeln($text);
        }

        return Command::SUCCESS;
    }
}

With autoconfiguration the command is found automatically, and php bin/console app:greet Ana --yell --times=2 works at once. php bin/console list shows it and php bin/console app:greet --help prints the help generated from configure(). The make:command maker generates the skeleton. Commands are services: put dependencies in the constructor (and call parent::__construct()), and the container autowires them. Because the name is in the attribute, Symfony can list the command without creating the object, so commands are lazy.

Symfony 7.3 added a shorter style in which a command has an __invoke() method and declares its input with #[Argument] and #[Option] attributes on the parameters. The classic configure() and execute() shown here work in every Symfony 7 release and are still what most code and bundles use.

Arguments and options

  • An argument is positional: app:greet Ana. It can be REQUIRED, OPTIONAL (with a default) or IS_ARRAY (the last argument collects the rest).
  • An option starts with -- and can have a one-letter shortcut: --yell or -y. Options are VALUE_NONE (a flag), VALUE_REQUIRED, VALUE_OPTIONAL or VALUE_IS_ARRAY (repeatable).

Use arguments for the thing the command acts on and options for switches that tune how. Every command also gets built-in options such as -v/-vv/-vvv (verbosity), -q (quiet) and -n (no interaction).

The exit code

execute() returns an integer. Command::SUCCESS is 0, Command::FAILURE is 1 and Command::INVALID is 2. The shell, cron and CI systems all read this number, so always return an honest one: a command that prints an error but exits with 0 will be reported as a success by your deploy pipeline.

Output that people can read

Plain $output->writeln() is enough for simple text, but SymfonyStyle gives you consistent, readable formatting:

PHP
// real Symfony, read-only
use Symfony\Component\Console\Style\SymfonyStyle;

protected function execute(InputInterface $input, OutputInterface $output): int
{
    $io = new SymfonyStyle($input, $output);

    $io->title('Importing customers');
    $io->section('Reading file');

    $io->table(
        ['Email', 'Status'],
        [['[email protected]', 'created'], ['[email protected]', 'skipped']],
    );

    foreach ($io->progressIterate($rows) as $row) {
        $this->importer->import($row);
    }

    $io->success('Imported 2 customers.');
    // $io->warning('...');  $io->error('...');  $io->note('...');

    return Command::SUCCESS;
}

SymfonyStyle also asks questions: $io->ask('Your name?', 'Anonymous'), $io->confirm('Delete everything?', false) and $io->choice('Environment', ['dev', 'prod'], 'dev'). When the command runs with --no-interaction, these return their default value, which keeps commands usable from cron and CI.

Verbosity levels let you show detail only on request: $output->isVerbose(), isVeryVerbose() and isDebug(), or the shortcut $output->writeln('...', OutputInterface::VERBOSITY_VERBOSE). Print errors to standard error with $io->error() or $output->getErrorOutput() (when the output is a ConsoleOutputInterface), so scripts can separate them from normal output.

flowchart LR
    A["bin/console app:greet Ana --yell"] --> App["Application<br/>finds the command by name"]
    App --> P["Input parsing<br/>against configure()"]
    P -->|"bad input"| E["Error message<br/>exit code 2"]
    P -->|"ok"| X["execute(input, output)"]
    X --> R["Exit code<br/>0 = success"]

The application resolves the command, parses and validates the input, runs execute() and returns its exit code to the shell.

Running the idea

Here is a plain-PHP stand-in for the first half: a command with declared arguments and options, an input parser that validates them, an output object, and exit codes. It is not Symfony's code, but the flow is the one in the diagram.

PHP Arguments, options and exit codes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first three runs succeed with different combinations of flag and option. The empty run fails validation before execute() is ever called and returns 2 (invalid), while the last one reaches execute() and chooses to fail with 1. That split is the same in Symfony: the Console component rejects malformed input itself, and your code decides about everything else.

Tables, progress bars and a test harness

Long-running commands should tell you how far they are, and they should be testable. Symfony's CommandTester runs a command with given input, with no real terminal, and lets you read the output and the exit code. This stand-in implements a table, a progress bar and a tester around an import command with a --strict option.

PHP Table, progress bar and a command tester (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The progress bar prints a new line per step here because there is no terminal to redraw; the real progress bar rewrites the same line. The checks at the bottom are exactly the kind of assertions you would write in a real test: output text and exit code, for different inputs, without touching a terminal.

In a Symfony project the equivalent test extends KernelTestCase, builds new Application(self::$kernel), finds the command with $application->find('app:import'), wraps it in new CommandTester($command) and calls execute(['--strict' => true]). After that, $commandTester->assertCommandIsSuccessful(), getStatusCode() and getDisplay() give you the checks above. The testing lesson covers the setup.

Habits of good commands

  • Keep execute() thin. Parse input, call a service, print the result. The business logic belongs in a service you can reuse from controllers and tests.
  • Be safe to run twice. Cron jobs overlap and people press Enter twice. Make commands idempotent or use a lock.
  • Make them non-interactive friendly. Give every question a sensible default and offer an option such as --force for destructive steps.
  • Return real exit codes, and send errors to the error stream.
  • For huge data sets, work in batches and free memory (for Doctrine, clear the entity manager now and then), because a command may process millions of rows in one process.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which attribute registers a class as a console command with a name and description?

    #[AsCommand(name: 'app:greet', description: '...')] tells Symfony the command's name, so it can list it and create it lazily.
  2. 2. What does a command signal to cron or a CI pipeline by returning Command::FAILURE?

    FAILURE is exit code 1. Schedulers and pipelines treat any non-zero code as an error.
  3. 3. What is the difference between an argument and an option?

    app:greet Ana is an argument. --yell and --times=2 are options, which are named and can be flags or carry values.
  4. 4. What does CommandTester let you do?

    CommandTester executes a command without a terminal and exposes getDisplay() and getStatusCode() for assertions.
  5. 5. A command asks $io->confirm('Delete everything?', false) and runs with --no-interaction. What happens?

    In non-interactive mode, questions return their defaults. A safe default of false prevents accidental destruction.

Summary

  • A command is a service class with #[AsCommand], a configure() method that declares arguments and options, and an execute() method that returns an exit code.
  • Arguments are positional; options are named switches or values with optional shortcuts. -v, -q and -n come for free.
  • SymfonyStyle provides titles, tables, progress bars, questions and result blocks; questions fall back to defaults in non-interactive mode.
  • Return Command::SUCCESS, FAILURE or INVALID honestly; cron and CI depend on it.
  • Test commands with CommandTester, keep execute() thin and make commands safe to run twice.

Next up: Mailer and Notifier.