Magento 2 - Create Custom Command Line to Magento 2 CLI Console

I'm trying to create an article to create custom command line, in summary what we need to do are:

  1. Define command on di.xml.

  2. Create new Console Class.

  3. Call the command

Define command on di.xml

First we need to define the command on di.xml, this for simple example we're going to use in this article:

Filepath: app/code/Fiko/Magento/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="FikoWelcome" xsi:type="object">Fiko\Magento\Console\Welcome</item>
            </argument>
        </arguments>
    </type>
</config>

Focus on item syntax, the rest are rule by magento in order to create custom command line.

  • name="FikoWelcome", it is the command name, it's the identity of this command.

  • xsi:type="object", the type of what's inside this item syntax, in this case it's object.

  • Fiko\Magento\Console\Welcome, magento 2 will call this class to be registered to magento as a custom command.

Create new Console Class

Then we need to create class for this custom command.

Filepath: app/code/Fiko/Magento/Console/Welcome.php

<?php

namespace Fiko\Magento\Console;

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

class Welcome extends Command
{
    protected function configure()
    {
        $this->setName('fiko:welcome');
        $this->setDescription('Demo description of welcoming someone!');

        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("Welcome Home!");
    }
}

configure and execute are default methods of creating custom command.

  • configure is a method to define name or identity we need to type on command line.

  • execute is default method that will handle the action.

Call the Command

Finally, in order to call the command you have already created, you need to setup:di:compile and cache:clear.

bin/magento setup:di:compile
bin/magento cache:clear

Then you can call it by executing

bin/magento fiko:welcome

Add Argument to Magento 2 Command

it's an optional and will be covered on next article, if you wish to add custom argument to your command line, you can visit this article.

Did you find this article valuable?

Support Fiko Borizqy by becoming a sponsor. Any amount is appreciated!