Magento 2 create custom command
Today we discuss how in Magento 2 create custom command. Sometime we need to import sample data or use the long queries to get data so for that it is better to use command line interface. Magento 2 use mostly command line interface for upgrade, reindex, static content deploy and many other command available. Here is list of default magento available command. So let’s start with our custom command.
Step 1: Define Command
For custom command keep in mind in item name qaisarSatti_helloworld first letter will your nameSpace. Now add following code to your 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="qaisarSatti_helloworld" xsi:type="object">QaisarSatti\HelloWorld\Console\Command\HelloWorld</item>
</argument>
</arguments>
</type>
</config>
Step 1: Create Command
Now Create file HelloWorld.php in following directory.
In your configure method just set
setName(‘qaisarsatti:helloworld’) // this will be your command that you run from cli
setDescription(‘Command Description’) // add your command detail
In you execute method you add your custom logic
namespace QaisarSatti\HelloWorld\Console\Command;
use \Symfony\Component\Console\Command\Command;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Output\OutputInterface;
class HelloWorld extends Command
{
public function __construct(
) {
parent::__construct();
}
protected function configure()
{
$this->setName('qaisarsatti:helloworld')
->setDescription('Just Checking for command'); //add you description here
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
try{
//add your logic here
$output->writeln('<info>Yahoooo command Successfully working!</info>');
} catch (\Exception $e) {
$output->writeln("<error>{$e->getMessage()}</error>");
}
}
}
Now check our command is listed or not. Just run following command
qaisarsatti
qaisarsatti:helloworld Just Checking for command
Now we execute the our command
The output will be shown
Now following this you can add new custom command in magento 2.