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.
Step1. Create module directory
Go to Magento app/code directory and create a directory with your vendor name. My vendor name is “CoolCodders”.
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/CoolCodders/CLICommnad”
Step2. Create module registration file
<?php
//file path: MAGENTO_ROOT/app/code/CoolCodders/CLICommnad/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'CoolCodders_CLICommnad',
__DIR__
);
Step3. Create module config file
<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/CoolCodders/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="CoolCodders_CLICommnad" setup_version="1.0.0" />
</config>
Step4. Create di.xml(dependency injection) config file
<?xml version="1.0"?>
<!-- file path: MAGENTO_ROOT/app/code/CoolCodders/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">CoolCodders\CLICommand\Console\Custom</item>
</argument>
</arguments>
</type>
</config>
Step5. Create CLI command logic file
<?php
//file path: MAGENTO_ROOT/app/code/CoolCodders/CLICommnad/Console/Custom.php
namespace CoolCodders\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('cool: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 */
}
}
Step6. Install your module to magento
php bin/magento module:enable CoolCodders_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