How to Add Command line in to Console CLI in Magento 2

Follow these steps add the command line in to console CLI in magento 2.

  • create the di.xml
  • create command class

Create di.xml file

 In di.xml file you will define the command.

Directory

app/code/VendorName/ModuleName/etc/di.xml 

Content of 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="demoCommand" xsi:type="object">VendorName\Module\Console\DemoCommand</item>
</argument>
</arguments>
</type>
</config>

Create Command Class

Directory

app/code/VendorName/ModuleName/Console/DemoCommand.php

Content of DemoCommand.php

<?php
namespace VendorName\ModuleName\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DemoCommand extends Command
{
protected function configure()
{
$this->setName('demo:command');
$this->setDescription('Demo command line');

parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("The Command Created");
}
}

 Now flush/clear the magento cache,

php bin/magento cache:clean

Run the created commmand:

php bin/magento demo:command



If you are looking for Magento Developers, visit Magento Developer Agency.