Module
-
Magento2 Cli Command
Today, We will create our custom module to add CLI Command.
First of all, you need to have basic knowledge of magento2 module.
We will create module : Mageclinics_Command
1. Module StructureOur module structure will be like below.
Basic module fileapp/code/Mageclinics/Command/registration.ph
papp/code/Mageclinics/Command/etc/module.xml
File for our CLI commandsapp/code/Mageclinics/Command/etc/di.xml
app/code/Mageclinics/Command/Console/Hello.php
2. Step 1: Command node in di.xml
create di.xml file, Use a type with name Magento\Framework\Console\CommandList to define the command option.
File: app/code/Mageclinics/Command/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="hello" xsi:type="object">Mageclinics\Command\Console\Hello</item>
</argument>
</arguments>
</type>
</config>3. Create Console class file
File: app/code/Mageclinics/Command/Console/Hello.php
<?php
namespace Mageclinics\Command\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 TEST = 'test';
protected function configure()
{
$options = [ new InputOption( self::TEST, null, InputOption::VALUE_REQUIRED, 'Test' ) ];
$this->setTest('example:hello')
->setDescription('Test command line')
->setDefinition($options);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($test = $input->getOption(self::TEST)) {
$output->writeln("Hello " . $test);
} else {
$output->writeln("Hello World");
}
return $this;
}
}configure() : function will set the name, description, command line arguments of the Magento 2 add command line
execute() : function will run when we run this command line via console.
4. Run command.
From Command line run php bin/magento list to see all available commands.
And you will see example:hello in the list of commands.
Once you run php bin/magento example:hello --test="John"
The result will be Hello John