09 Jun, 2021
Today we going to create a new custom CLI command in Magento 2.x
Console command is usefull to run you program from CLI. We will going to create new CLI command in magento 2.x. Magento 2 provide so many CLI commands, We will add our custom CLI commnad in Magento 2. It's very simple to add our custom CLI command in Magento 2.
Let's start by creating a CLI command.
Go to Magento app/code directory and create a directory with your vendor name. My vendor name is "RS".
After creating the vendor directory, need to create a directory for the module. My module name is "CLICommnad".
My custom module directory path is like "MAGENTO_ROOT/app/code/RS/CLICommnad"
<?php
//file path: MAGENTO_ROOT/app/code/RS/CLICommnad/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'RS_CLICommnad',
__DIR__
);
<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/RS/CLICommnad/etx/module.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="RS_CLICommnad" setup_version="1.0.0" />
</config>
<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/RS/CLICommnad/etx/di.xml -->
<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="custom_command" xsi:type="object">RS\CLICommand\Console\Custom</item>
</argument>
</arguments>
</type>
</config>
<?php
//file path: MAGENTO_ROOT/app/code/RS/CLICommnad/Console/Custom.php
namespace RS\CLICommnad\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
class Custom extends Command
{
protected function configure()
{
$this->setName('rs:custom-cli')
->setDescription('Custom CLI command');
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Magento 2.x custom CLI command');
/* Put you logic here */
}
}
php bin/magento module:enable RS_CLICommnad
php bin/magento setup:di:compile
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
That's the steps to create a custom CLI command in Magento 2.x
RAJU SADADIYA (MAGENTO DEVELOPER)