Custom CLI commands Magento 2
Magento 2 enables your component to add commands to the default CLI
Magento has one command-line interface that performs both installation and configuration tasks:
I am explaining here a way to add custom commands for your module.
1) Create a Command class, I have created a custom class
at app/code/DW/Interface/Console/OrderCron.php.
<?php
/**
* @author DW
* @copyright Copyright (c) 2019 DecryptWeb (https://www.decryptweb.com/)
*/
namespace DW\Interface\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use DW\Interface\Cron\OrderUpdate;
/**
* Class for OrderCron
*/
class OrderCron extends Command
{
/**
* @var string
*/
const ST = 'st';
const ET = 'et';
/**
* @var orderupdate
*/
protected $orderUpdate;
/**
* OrderCron constructor.
*
* @param OrderUpdate $orderUpdate OrderUpdate
* @param string|null $name string
*/
public function __construct(
OrderUpdate $orderUpdate,
string $name = null
) {
$this->orderUpdate = $orderUpdate;
parent::__construct($name);
}
/**
* OrderCron Configure
*/
protected function configure()
{
$options = [
new InputOption(
self::ST,
null,
InputOption::VALUE_OPTIONAL,
'StartDate'
),
new InputOption(
self::ET,
null,
InputOption::VALUE_OPTIONAL,
'EndDate'
),
];
$this->setName('order:post:send');
$this->setDescription('Send order to ERP);
$this->setDefinition($options);
parent::configure();
}
/**
* @param InputInterface $input InputInterface
* @param OutputInterface $output OutputInterface
* @return int|void|null
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->orderUpdate->execute($input->getOption(self::ST), $input->getOption(self::ET)); //call custom function along with arguments
}
}
2) Declare your Command class in Magento\Framework\Console\CommandList and configure the command name using dependency injection (app/code/DW/Interface/etc/di.xml)
<!-- Custom command -->
<type name="Magento\Framework\Console\CommandList">
<arguments>
<argument name="commands" xsi:type="array">
<item name="orderUpdateCron" xsi:type="object">DW\Interface\Console\OrderCron</item>
</argument>
</arguments>
</type>
3) Clean the cache:
bin/magento cache:clean
4) Regenerate the code:
bin/magento setup:di:compile
As a result, the new command order:post:send that accepts multiple parameters is ready to use.
bin/magento order:post:send --st='2019-01-01' --et='2019-02-01'
Hope this is helpful
