Add New Command Magento 2

Follow the below steps to create new command line in to Console CLI in Magento 2.

Define command in di.xml

In di.xml file, you can use a type with name Magento\Framework\Console\CommandList to define the command option.

File: app/code/PHPCodez/First/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="displayPHPCodez" xsi:type="object">PHPCodez\First\Console\Hello</item>
 </argument>
 </arguments>
 </type>
</config>

This config will declare a command class hello. This class will define the command name and execute() method for this command.

Create command class

As define in di.xml, we will create a command class:

File: app/code/PHPCodez/First/Console/Hello.php

<?php

namespace PHPCodez\First\Console;

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

class Hello extends Command
{
 protected function configure()
 {
 $this->setName('phpcodez:Hello');
 $this->setDescription('Demo command line');
 
 parent::configure();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
 $output->writeln("Hello PHPCodez");
 }
}

In this function, we will define 2 methods:

configure() method is used to set the name, description, command line arguments of the magento 2 add command line

execute() method will run when we call this command line via console.

Clean the cache from shell and run the command hello.

php bin/magento cache:flush
php bin/magento phpcodez:hello

Command With Arguments

Modify Hello.php with the following content

File: app/code/PHPCodez/First/Console/Hello.php

<?php

namespace PHPCodez\First\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 Hello extends Command
{

const NAME = 'name';

protected function configure()
 {

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

$this->setName('phpcodez:hello')
 ->setDescription('Demo command line')
 ->setDefinition($options);

parent::configure();
 }

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

$output->writeln("Hello " . $name);


 } else {

$output->writeln("Hello PHPCodez");

}

return $this;

}
}

Clean the cache from shell and run the command hello.

php bin/magento cache:flush
php bin/magento phpcodez:hello --name PHPCodez

Output will be Hello PHPCodez

Share

Leave a Reply

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