How to create new command in magento2

Step1:- Declare module in etc/module.xml


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Ecommoco_Command" setup_version="1.0.0" />
</config>

Step2: Register module in registration.php


<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Ecommoco_Command',
__DIR__
);

Step3: Declare command in etc/di.xml


<?xml version="1.0"?>
<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="firstcommand" xsi:type="object">Ecommoco\Command\Console\Firstcommand</item>
</argument>
</arguments>
</type>
</config>

Step4: Create the class for execution


<?php
namespace Ecommoco\Command\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Firstcommand extends Command
{
protected function configure()
{
$this->setName('ecommoco:first');
$this->setDescription('First Command');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("First command");
}
}

Activate the module

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s