Creating custom console command in Magento 2

In Magento 2, Many application we need to do perform many things after did any deployment. Or other similar thing that we need to do every time or do perform that some specific of time. In that case we can use Magento cron or also we can create one console command for the same.

Like if we need to perform anything after the deployment then the console command is good thing to do. We need to implement all the thing in one console command.

When we run deployment commnad and once it’s completed so we just need to run our custom console command, it’s run everything that we need to perform everytime when we do deployment.

Let’s create small module for console command.

Register our custom module to Magento application

We need to create registration.php file for register our custom module in Magento 2.

//file path: MAGENTO_ROOT/app/code/RS/SimpleCmd/registration.php

Configure module version and module dependency

We need to create module.xml file for configure module version and module dependency.

<?xml version="1.0" ?>
<!-- file path: MAGENTO_ROOT/app/code/RS/SimpleCmd/etc/module.xml -->
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="RS_SimpleCmd" setup_version="1.0.0">

Register your custom console command in Magento application

Using di.xml we can register our custome commnad in Magento 2 Application. We need to add arguments on Magento\Framework\Console\CommandList this class adds the new console command in Magento 2. In that argument we need to give command class and command name.

<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/RS/SimpleCmd/etc/di.xml -->
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
            <argument name="commands" xsi:type="array">
                <item name="simplecmd" xsi:type="object">RS\SimpleCmd\Console\Simple</item>

Creating the console command class

Magento 2 create console command using symfony library. We create console command extending of the symfony library class.

//file path: MAGENTO_ROOT/app/code/RS/SimpleCmd/Console/Simple.php 
namespace RS\SimpleCmd\Console;

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

class Simple extends Command
    protected function configure()
        $this->setDescription('This is simple command for demo');

    protected function execute(InputInterface $input, OutputInterface $output)
        $output->writeln('Hi, Your custom command is called and executed successfully!');
        return \Magento\Framework\Console\Cli::RETURN_SUCCESS;

Let’s check the output.


Custom console command in Magento command list.

Custom command output

That’s all for create custom console command in Magento 2 application.