Programmatically: How to create a custom CLI command in Magento
Step 1: Create a new module
Create a new directory CustomCli inside the app/code/local directory. Inside this directory, create the following files: CustomCli/etc/module.xml:
<?xml version="1.0"?>
<config>
<modules>
<CustomCli>
<version>1.0.0</version>
</CustomCli>
</modules>
</config>
CustomCli/etc/config.xml:
<?xml version="1.0"?> <config> <modules> <CustomCli> <active>>true</active> <codePool>local</codePool> </CustomCli> </modules> </config>
Step 2: Create the CLI command
Create a new file CustomCli/Model/Command.php:
use Magento\Framework\Setup\Template;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CustomCliCommand extends Command
{
protected function configure()
{
$this->setName('custom-cli');
$this->setDescription('Run custom CLI command');
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Your custom code here
$output->write('Hello, world!');
}
}
Step 3: Register the CLI command
Add the following code to CustomCli/etc/command.xml:
<?xml version="1.0"?> <config> <cliCommands> <custom-cli translate="label"> <label>Custom CLI Command</label> <module>CustomCli</module> <class>CustomCli\Model\Command</class> </custom-cli> </cliCommands> </config>
Step 4: Enable the module
php bin/magento module:enable CustomCli
php bin/magento module:enable CustomCli
Step 5: Run the CLI command
Run the following command in your terminal:
php bin/magento custom-cli