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:
1. Create registration.php file in app\code\[Vendor]\[Namespace]\
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, '[Vendor]_[Namespace]', __DIR__ );
2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc
<?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>
3. Create di.xml file in app\code\[Vendor]\[Namespace]\etc
<?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>
4. Create Ping.php in [Vendor]\[Namespace]\Model
<?php namespace [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:
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.
Thanks.