Add Console Commands in Magento 2

Magento comes with a predefined list of Symfony based CLI commands that perform specific actions, such as deploying static content or clearing the cache. A developer has the ability to add console commands in Magento 2 by adding a module and configuring the command.

By adding the usual registration.php and etc/module.xml files within your module’s directory, the command configuration can begin.

As with most Magento functionality, the configuration is defined within XML files, and for command-specific configuration, this resides within the module’s di.xml file.

The example below shows configuration for a sayhello command that belongs within a pair of <type> nodes.

// app/code/[Vendor]/[module]/etc/di.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\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="sayhello" xsi:type="object">[Vendor]\[Module]\Model\SayHello</item>
            </argument>
        </arguments>
    </type>
</config>

If adding multiple commands within multiple Magento modules, the contents within di.xml will mostly be identical apart from the name attribute of the <item> node, that specifies the sayhello command. In addition, the value within the pair of <item> nodes that contains the model class will also differ. This class contains the functionality you want to execute when running your specific command.

For simplicity, the class in this example will output ‘Hello World!’ in the console using writeln() from the Symfony\Component\Console\Output\OutputInterface interface.

Within the protected configure() method, you can set the name and description of the command.

<?php
namespace [Vendor]\[Module]\Model;

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

class SayHello extends Command
{
    protected function configure()
    {
        $this->setName('custom:sayhello')
            ->setDescription('Here you can add some description about the command.');

        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Hello World!');
    }
}

Assuming you have successfully registered and enabled your module, you can run the newly added custom:sayhello command from the Magento root directory and see the output.

$ /path/to/your/php bin/magento custom:sayhello
Hello World!

Whilst the command in this example is pretty useless, commands are commonly used by developers to perform mass actions, such as clearing the contents of the var/generation folder, or mass importing/deleting entities such as order or customer data on development environments.

Your custom command will also be added to the command list when passing in the --list argument when using the bin/magento command.

$ /path/to/your/php bin/magento --list

Available commands:
 help                                      Displays help for a command
 list                                      Lists commands
admin
 admin:user:create                         Creates an administrator
 admin:user:unlock                         Unlock Admin Account
app
 app:config:dump                           Create dump of application
cache
 cache:clean                               Cleans cache type(s)
 cache:disable                             Disables cache type(s)
 cache:enable                              Enables cache type(s)
 cache:flush                               Flushes cache storage used by cache type(s)
 cache:status                              Checks cache status
catalog
 catalog:images:resize                     Creates resized product images
 catalog:product:attributes:cleanup        Removes unused product attributes.
cron
 cron:run                                  Runs jobs by schedule
[module]
 custom:sayhello                           Here you can add some description about the command.

Note: This article is based on Magento Open Source version 2.1.8.