Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 42 ยท Admin, APIs and Backend Services

Custom CLI Commands

Write your own bin/magento commands in Magento 2.4: extend the Symfony Console Command, add arguments and options, register through di.xml, and practise with a runnable console stand-in.

Every task you run with bin/magento is a console command: cache:flush, indexer:reindex, setup:upgrade and hundreds more. When your module needs a task that a developer or a server should run on demand, such as importing a CSV, cleaning old rows or rebuilding a report, you add your own command. Commands are also the best way to run long jobs, because the command line has no web server timeout and no browser waiting on the other end.

Magento's commands are built on the Symfony Console component, the same library behind Laravel's Artisan and Composer. You write a class that describes a name, arguments and options, and a method that does the work. Then you tell Magento's dependency injection system about the class in di.xml, and bin/magento list shows it. This lesson covers each of those steps. If command-line PHP is new to you, read Command-Line PHP first.

Anatomy of a command

Here is a complete command in a hypothetical Acme_Hello module. This is real Magento code, so it is read-only here:

PHP
<?php
declare(strict_types=1);

namespace Acme\Hello\Console\Command;

use Acme\Hello\Model\Greeter;
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;

class GreetCommand extends Command
{
    public function __construct(
        private readonly Greeter $greeter,
        ?string $name = null
    ) {
        parent::__construct($name);
    }

    protected function configure(): void
    {
        $this->setName('acme:greet')
            ->setDescription('Prints a greeting')
            ->addArgument('name', InputArgument::OPTIONAL, 'Who to greet', 'world')
            ->addOption('shout', 's', InputOption::VALUE_NONE, 'Use capital letters')
            ->addOption('times', null, InputOption::VALUE_REQUIRED, 'Repeat count', '1');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $text = $this->greeter->greet((string) $input->getArgument('name'));
        if ($input->getOption('shout')) {
            $text = strtoupper($text);
        }
        for ($i = 0; $i < (int) $input->getOption('times'); $i++) {
            $output->writeln($text);
        }

        return Command::SUCCESS;
    }
}

Four details matter:

  • configure() declares the interface of the command: its name (vendor:topic:action is the usual style), a description, and its arguments and options. It runs when the command object is created.
  • Arguments are positional (bin/magento acme:greet Ada). They can be required, optional, or arrays. Options are named (--times=3) and may have a one-letter shortcut (-s). VALUE_NONE options are on/off flags.
  • execute() does the work and returns an integer exit code. Command::SUCCESS is 0 and Command::FAILURE is 1. Shells, deployment scripts and cron jobs use that number to know whether the command worked, so never return success after a failure.
  • The constructor can take dependencies like any other Magento class. You must call parent::__construct(), otherwise Symfony never runs configure().

The same code could be written with setName() called from the constructor or with PHP attributes in newer Symfony versions. The configure() style above is the one you will find in almost all Magento code, so use it.

Registering the command

A command does nothing until Magento knows it exists. Registration is a di.xml entry that adds your class to the list of commands. The file goes in etc/di.xml of your module:

XML
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandListInterface">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="acmeGreet" xsi:type="object">Acme\Hello\Console\Command\GreetCommand</item>
            </argument>
        </arguments>
    </type>
</config>

Several modules can each add an <item> to the same commands array, and Magento merges them. The item name (acmeGreet) only has to be unique within the array, so prefix it with your vendor name. After adding a new command, clear generated and cached configuration (bin/magento cache:flush, and in production mode bin/magento setup:di:compile) so the new di.xml is read. Then bin/magento list acme should show the command.

flowchart LR
    A["bin/magento acme:greet Ada -s"] --> B["Application builds<br/>CommandList from di.xml"]
    B --> C["Symfony finds the command<br/>by name"]
    C --> D["Input parsed against<br/>arguments and options"]
    D --> E["execute() runs<br/>and returns an exit code"]

The CLI application collects every registered command, matches the name, parses the input and calls execute().

A stand-in console

Real Magento builds the command list from di.xml and lets Symfony parse the input. The first example below imitates both parts in plain PHP. The $commands array plays the role of the <argument name="commands"> list, and the base class mimics the Symfony contract: a name, a description and an execute() that returns an exit code. The parsing is skipped here because the input is already split into arguments and options.

PHP A command registry and exit codes

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.

Notice that GreetCommand receives its Greeter through the constructor, exactly like in Magento, and that the application never calls new on commands itself.

Parsing arguments and options

Symfony does the parsing in real life, but knowing the rules helps you design a good command line. A token starting with -- is a long option, --times=3 carries a value, -s is a shortcut, and anything else is a positional argument filled in the order the arguments were declared. A required argument that is missing, or an option that was never declared, makes the command fail before execute() runs.

PHP A tiny argv parser

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 fourth case shows why a command should declare its arguments properly: the caller gets a clear message instead of a half-run import.

The parser above is a teaching stand-in. Symfony's real input handling also supports short option clusters like -vvv, array arguments, defaults, and automatic --help output generated from your configure() calls.

Writing commands that behave well

  • Keep the constructor light. Magento builds every registered command each time you run any bin/magento command, even cache:flush. A command that injects a heavy service pulls that service into every run. Inject a Proxy instead (see Factories, Proxies and Generated Code) or a factory that creates the object inside execute().
  • Set the area when you need it. The CLI runs without a frontend or admin area. If your code uses services that need an area, such as some emulation or translation features, inject Magento\Framework\App\State and call setAreaCode('adminhtml') at the start of execute(). Wrap it in a try block, because it throws if the area was already set.
  • Write to the output object, not echo. $output->writeln() supports verbosity levels and colour tags such as <info>Done</info> and <error>Failed</error>, and it can be captured in tests.
  • Return a real exit code. Catch expected exceptions, print a clear message and return Command::FAILURE. A script or cron job depends on it.
  • Offer --dry-run for destructive tasks. Print what would change and change nothing.
  • Process big data in batches. A command has no timeout, but PHP still has a memory limit. Page through records instead of loading everything, as covered in Collections, Filters and SearchCriteria.
  • Reuse your services. The command should be a thin shell around a service class that a cron job, an observer or an API can also call. Then the logic is tested once and shared.

A command can do as much damage as an admin user, and it often runs as the same Linux user that owns the Magento files. Treat arguments as untrusted input, validate them, and never build SQL or shell commands by concatenating them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a Magento module make a new command appear in bin/magento list?

    The commands argument of CommandListInterface is an array merged from every module's di.xml. Each item names a command class, and Magento instantiates it through dependency injection.
  2. 2. What does execute() return, and why does it matter?

    execute() returns an int: 0 (Command::SUCCESS) for success and non-zero for failure. Deployment scripts check it.
  3. 3. Why must a command constructor call parent::__construct()?

    The Symfony Command constructor calls configure(). Skipping it leaves the command without a name and definition.
  4. 4. Why should a command avoid injecting heavy services directly into its constructor?

    Magento creates all registered commands to build the list. Use proxies or factories so expensive objects are created only when execute() needs them.

Summary

  • A custom command extends Symfony's Command, declares its name, arguments and options in configure(), and does its work in execute().
  • execute() returns an exit code: Command::SUCCESS or Command::FAILURE.
  • Register the class as an item of the commands array of CommandListInterface in etc/di.xml, then flush the cache (and compile in production mode).
  • Keep constructors light, use proxies or factories for heavy dependencies, set the area code when required, and put real logic in reusable services.
  • Validate every argument, support --dry-run for destructive jobs, and write output through the output object.

Next: Indexers and Caching