This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Add Custom CLI Commands In Magento 2

Published on February 12, 2018 - Content Updated on

4 Min Read

The new command line interface (CLI) enables Magento developers to use default command provided by Magento modules. Using this, developers could manage modules, carry our database updates, manage indexes and generate classes.

The great thing is that Magento developers could now create Magento 2 CLI command for their modules. While this is great, developers should always make sure that they observe the best code writing standards as defined by the Magento dev community.

Add Custom Magento 2 Command

The process to create Magento 2 command is simple. In this tutorial, I will not go into the details of creating a Magento 2 module.

Just create a simple module Cloudways_Commandline with etc/module.xml and registration.php files included in the root of module’s directory.

Scale Your Magento Store With Ease

One-Click Magento installation with your own managed hosting solution.

Now, create a di.xml file in the etc directory of your module. Insert the following code in the file:

<?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="CloudwaysHicustomer" xsi:type="object">Cloudways\Commandline\Console\Hicustomer</item>

           </argument>

       </arguments>

   </type>

</config>

As you can see, I have added an entry in di.xml file. The <type> tag is pointing to Magento\Framework\Console\CommandList class. Furthermore, it has the <argument> named commands, and the <item>  tag. It seems like Magento 2 is doing some magic by sending the argument to CommandList class. That is how dependency injection works – injecting the Command object (defined in the <item> tag) into an array of all commands.

I have also declared a class Cloudways\Commandline\Console\Hicustomer in the <item> tag. This class will set the name, and description of command using the configure() method. The class will also define the execute() method for the command.

Create Class for Magento 2 Console Command

The next step is the creation of the class file Hicustomer.php (as defined in di.xml), in the Console directory of the module and add the following code to it:

<?php

namespace Cloudways\Commandline\Console;

 

use Symfony\Component\Console\Command\Command;

use Symfony\Component\Console\Input\InputInterface;

use Symfony\Component\Console\Output\OutputInterface;

 

class Hicustomer extends Command

{

   protected function configure()

   {

       $this->setName('cloudways:hicustomer');

       $this->setDescription('Demo command line');

      

       parent::configure();

   }

   protected function execute(InputInterface $input, OutputInterface $output)

   {

       $output->writeln("Hi Customer");

   }

}

The Hicustomer class has two methods. The configure() method is used to set initial configuration (such as name, description, and arguments) for the command. The execute() method will contain the logic that would be executed when the CLI command is called in the console.

Run the Added Magento 2 CLI Command

Once the class has been declared, enable the module, run the setup upgrade command and flush Magento 2 cache. Now, type the following CLI command to see the list of all available Magento 2 commands.

php bin/magento list

You will notice that the custom CLI command is also on the list.

Magento Custom CLI Command Display

Now, run the php bin/magento cloudways:hicustomer command to see the desired result.

Magento Custom Argument CLI Command

Add Argument to Magento 2 created CLI Command

Add Argument to Custom Magento 2 Command

This was just a basic CLI command. To make things interesting, I will now demonstrate how to add an argument to the custom Magento command. For this, replace the current contents of the class file Hicustomer.php with the following.

<?php

namespace Cloudways\Commandline\Console;

 

use Symfony\Component\Console\Command\Command;

use Symfony\Component\Console\Input\InputInterface;

use Symfony\Component\Console\Output\OutputInterface;

use Symfony\Component\Console\Input\InputOption;

 

class Hicustomer extends Command

{

   const CUSTOMERNAME = 'Name';

 

   protected function configure()

   {

       $commandoptions = [new InputOption(self::CUSTOMERNAME, null, InputOption::VALUE_REQUIRED, 'Name')];

 

       $this->setName('cloudways:hicustomer');

       $this->setDescription('Demo command line');

       $this->setDefinition($commandoptions);

      

       parent::configure();

   }

   protected function execute(InputInterface $input, OutputInterface $output)

   {

       if ($customername = $input->getOption(self::CUSTOMERNAME))

       {

         $output->writeln("Hi ".$customername);

       }

       else

       {

         $output->writeln("Hi Customer");

       }

   }

}

As you can see, I have created and added the Name argument for custom Magento command in configure() method using $this->setDefinition($commandoptions); function and get it in execute() method.

Once again, run setup upgrade command and flush Magento 2 cache. Invoke the custom CLI command by php bin/magento cloudways:hicustomer –Name=”Fayyaz” and it will show “Hi Fayyaz” as an output.

Custom CLI Command Output

Final Words!

In this tutorial, I have covered the basics to create Magento 2 CLI commands and explored the best way of adding a new CLI Command in Magento 2. I hope you have found this tutorial useful. If you have any feedback, feel free to share it in the comments section below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Great speed, features, knowledgebase, dashboard, UX and fast, expert support. Very happy!”

Stefan [Management Consultant]

Fayyaz Khattak

Fayyaz, a passionate Motorbike tourist, works as a Team Lead — Magento Community at Cloudways - A Managed Magento Hosting Platform. His objective is to learn & share about PHP & Magento Development in Community. You can contact him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!