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: /bin/magento.

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.

 * @author DW
 * @copyright Copyright (c) 2019 DecryptWeb (
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;

     * OrderCron Configure
    protected function configure()
        $options = [
            new InputOption(
            new InputOption(

        $this->setDescription('Send order to ERP);


     * @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">
    <argument name="commands" xsi:type="array">
        <item name="orderUpdateCron" xsi:type="object">DW\Interface\Console\OrderCron</item>

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top