How to Add Command line in to Console CLI in Magento 2
We will use an example module Mageplaza_Example to demo for this lesson. To add an option to Magento 2 CLI, we will follow by some steps:
Step 1: Define command in di.xml
Indi.xml
file, you can use a type with name Magento\Framework\Console\CommandList
to define the command option.File:
app/code/Mageplaza/HelloWorld/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="exampleSayHello" xsi:type="object">Mageplaza\HelloWorld\Console\Sayhello</item>
</argument>
</arguments>
</type>
</config>
Sayhello
. This class will define the command name and execute()
method for this command.Step 2: Create command class
As define in di.xml, we will create a command class:File:
app/code/Mageplaza/HelloWorld/Console/Sayhello.php
<?php
namespace Mageplaza\HelloWorld\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Sayhello extends Command
{
protected function configure()
{
$this->setName('example:sayhello');
$this->setDescription('Demo command line');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("Hello World");
}
}
configure()
method is used to set the name and the description of the magento 2 add command lineexecute()
method will run when we call this command line via console.
php magento --list
Now you can run the command to see the result
Next tutorial: Command Line Interface CLI »
Module Development Series
- Using VirtualType
- UI Bookmark Component
- Sticky Header Component
- Prompt Widget
- Plugin - Interceptor
- Add an URL Rewrite