How to create new command in Magento 2? - Kishan Savaliya

Welcome to Kishan Savaliya's Magento 2 Blog. In Magento 2, there are so many commands for different purpose. You can create your custom command as well there. If you don't know how to create new command in Magento 2, then this article can be useful to you. I will show you step by step guidance in this blog post, hope you may like this.

So let's start with basic steps first.. First of all you should have any custom module in your Magento. If you don't have it, then do not need to worry, you can create your custom module by following this article easily, click on this link I have added steps how to create your custom module in Magento 2?

In new custom command, we will try to print current date and time via command. Follow below steps now..

Step - 1 : Create Command Class.

In this step, you need to create Command class inside your module, so navigate to your magento root and then in your module directory. Create Console/Command directory inside your module.

app/code/SK/CustomCommand/Console/Command/NewCommandExample.php

Content for this file is..

<?php
/**
 * SK Custom Command in Magento 2.
 */

namespace SK\CustomCommand\Console\Command;

use \Symfony\Component\Console\Input\{InputInterface, InputArgument, InputOption};
use \Symfony\Component\Console\Output\OutputInterface;
use \Symfony\Component\Console\Command\Command;

class NewCommandExample extends Command
{
	protected function configure()
    {
        $this->setName('sk:custom-command:execute');
        $this->setDescription('SK Custom Command in Magento 2.');
        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln(date("Y-m-d H:i:s"));
        return $this;
    }
}

Step - 2 : Declare and configure your new command using dependency injection.

Create di.xml file inside etc/ directory in your module

app/code/SK/CustomCommand/etc/di.xml
  • Declare your Command class in Magento\Framework\Console\CommandListInterface

Content for this file is..

<?xml version="1.0"?>
<!--
/**
 * SK Custom Command in Magento 2.
 */
-->
<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="sk_custom_command_example" xsi:type="object">SK\CustomCommand\Console\Command\NewCommandExample</item>
            </argument>
        </arguments>
    </type>
</config>

Step - 3 : Run below commands in terminal

Now, you can run below command in your terminal to clear cache and regenerate code.

php bin/magento cache:clean
php bin/magento setup:di:compile

After successful compilation, you can check your new command in Magento command list using below command.

php bin/magento list

How to create new command in Magento 2?

Yes, it's there in list. So now we can execute that command same as all other Magento commands. ;-)

So let's run our new command

php bin/magento sk:custom-command:execute

How to create new command in Magento 2?

It's working. ;-)

We can pass arguments in command as well, so let's see one example how we can use it. For example we will pass product id in command argument and it will return product's name if that product exist in system, otherwise it will display error message. So let's start.

Go to your Command class

app/code/SK/CustomCommand/Console/Command/NewCommandExample.php

Content for this file is..

<?php
/**
 * SK Custom Command in Magento 2.
 */

namespace SK\CustomCommand\Console\Command;

use \Symfony\Component\Console\Input\{InputInterface, InputArgument, InputOption};
use \Symfony\Component\Console\Output\OutputInterface;
use \Symfony\Component\Console\Command\Command;

class NewCommandExample extends Command
{
    const PRODUCT_ID = 'product_id';

    protected $_productRepository;

    public function __construct(
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->_productRepository = $productRepository;
        parent::__construct();
    }

	protected function configure()
    {
        $this->setName('sk:custom-command:execute');
        $this->setDescription('SK Custom Command in Magento 2.');
        $this->addOption(
                self::PRODUCT_ID,
                null,
                InputOption::VALUE_REQUIRED,
                'PRODUCT ID'
            );
        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln(date("Y-m-d H:i:s"));
        $productId = $input->getOption(self::PRODUCT_ID);
        try{
            if($productId){
                $product = $this->_productRepository->getById($productId);
                $output->writeln("<info>Product name is : ".$product->getName()."</info>");
            }else{
                $output->writeln("<comment>Please enter product id in command argument.</comment>");
            }
        }catch(\Exception $e){
            $output->writeln("<error>".$e->getMessage()."</error>");
        }
        return $this;
    }
}

Now, you have to regenerate code using below command and clear Magento 2 cache and you can execute below commands one by one and check output.

php bin/magento setup:di:compile
php bin/magento cache:clean && php bin/magento cache:flush
php bin/magento sk:custom-command:execute
php bin/magento sk:custom-command:execute --product_id=1
php bin/magento sk:custom-command:execute --product_id=99999

Output :

How to create new command in Magento 2?

In first command, I didn't passed product id as an argument, so it's display comment message in yellow color. so in case, if you want to display any comment in command output then you can use <comment></comment>.

If you want to display any error message then you can use <error></error> and that text will appear in red background, and you can use <info></info> it'll display green color text in output.

Hope you may like this article and can understand this easily. You can add comments below in case if you have any questions regarding this article or if I missed anything here. I will check and get back to you with proper solution.

If you enjoyed this blog post, share it with friends!