There are certain tasks that you do in a Magento 2 store that are mundane and repetitive and, unfortunately, they’re also often the most important. For example, running a custom cron after a fixed time period, or remove a directory after caching.
However, you can turn many of these boring processes into one-command affairs by using the below method to create console command in Magento 2.
The custom console commands in Magento 2 are very helpful when you want to perform tasks that are repetitive and are to be done in the same manner every time!
Here, I’ve taken a simple example to display a message when a custom Magento 2 CLI command is run:
Steps to Create Console Command in Magento 2:
- Create registration.php file in app\code\[Vendor]\[Namespace]\123456<?php\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'[Vendor]_[Namespace]',__DIR__);
- Create module.xml file in app\code\[Vendor]\[Namespace]\etc1234<?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="[Vendor]_[Namespace]" setup_version="1.0.0"/></config>
- Create di.xml file in app\code\[Vendor]\[Namespace]\etc12345678910<?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="clean" xsi:type="object">[Vendor]\[Namespace]\Model\Ping</item></argument></arguments></type></config>
- Create Ping.php in [Vendor]\[Namespace]\Model1234567891011121314151617181920212223<?phpnamespace [Vendor]\[Namespace]\Model;use \Symfony\Component\Console\Command\Command;use \Symfony\Component\Console\Input\InputInterface;use \Symfony\Component\Console\Output\OutputInterface;class Ping extends Command{protected function configure(){$this->setName('meetanshi:ping')->setDescription('Ping us to support!');parent::configure();}protected function execute(InputInterface $input, OutputInterface $output){$output->writeln('Need Help Contact To Meetanshi.com!');}}
Run following command:
1 | bin/magento meetanshi:ping |
The output message will be “Need Help Contact To Meetanshi.com”
Similarly, you can use the function execute() to create console command in Magento 2 as per your requirements.
Please use the Comments section below to mention any doubts and I’d be happy to help 🙂
Thanks.
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.