Magento 2 : Create Custom Command Line in Console

We will learn how to add a command line to the Magento 2 console CLI in this tutorial. In Magento 2, a command line interface is added for quick feature changes.

CLI can be used in magento for ,Setting up Magento (and related tasks such as creating or updating the database schema, creating the deployment configuration, and so on),Caching clearing,index management, including reindexing,constructing translation packages and dictionaries,generating the dependency injection settings for the object management and creating classes that don’t exist, like factories and interceptors for plug-ins.
It is also used for static view files to deploy,Making CSS with LESS

For this lesson’s demonstration, we’ll utilise the example module Gm_module. In this example I will create a command to generate a detail of a product i.e name and sku . We will pass the Id of the product to the CLI and it will return the name and sku on the same command line console.

app/code/Gm/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="searchProducts" xsi:type="object">Gm\Module\Console\SearchProduct</item>
            </argument>
        </arguments>
    </type>
</config>
app/code/Gm/Module/Console/SearchProduct.php
<?php

namespace Gm\Module\Console;

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

class SearchProduct extends Command
{

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

    const PRODUCT_ID = 'id';

    protected function configure()
    {
        $options = [
            new InputOption(
                self::PRODUCT_ID,
                null,
                InputOption::VALUE_REQUIRED,
                'Name'
            )
        ];

        $this->setName('search:product')
            ->setDescription('Search Product By Id')
            ->setDefinition($options);

        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($Id = $input->getOption(self::PRODUCT_ID)) {

            $output->writeln("Searching For Id " . $Id);
            $Product = $this->productRepository->getById($Id);
            $output->writeln("Product Name = " . $Product->getName());
            $output->writeln("Product Sku = " . $Product->getSku());

        } else {

            $output->writeln("Please Select A Product");

        }

        return $this;
    }
}

We shall define 2 methods in this Class:

The Magento 2 add command line’s name, description, and command line parameters are specified using the configure() method.
When we invoke this command line via the console, the execute() method will be called.
Please clear Magento’s cache after declaring this class, then enter the following command:

bin/magento list

You Will be able to see your custom command in the list. Once You See It in the list you will be able to run your command.

bin/magento search:product --id=45294

Leave a Comment

Your email address will not be published. Required fields are marked *