In this article, we will show you how to state CLI commands in Magento 2 Module by the following steps:
Step 1: State CLI commands in di.xml
Step 2: Form command class in your custom module
Step 3: you will get the result
Magento 2 offers a new solution to run the commands which take a lot of Server’s resource (RAM or CPU). It’s using CLI commands. The below mention reindex command which runs in the console.
php bin/magento indexer:reindex
Sometime you want to use CLI commands in your module. How can we state these commands in a custom module of Magento 2? It’s simple; please follow the simple steps below.
Step 1: State CLI commands in di.xml
- State CLI commands in di.xml
/app/code/[NameSpace]/[ModuleName]/etc/di.xml
<type name="Magento\Framework\Console\CommandList"> <arguments> <argument name="commands" xsi:type="array"> <item name="active_users" xsi:type="object">[NameSpace]\[ModuleName]\Console\Command\ActiveUsersCommand</item> </argument> </arguments> </type>
- For example, I state the active_users command in di.xml
Step 2: Form command class in your custom module
- Form a command class in your custom module
/app/code/[NameSpace]/[ModuleName]/Console/Command/ActiveUsersCommand
<?php namespace [NameSpace]\[ModuleName]\Console\Command; use Symfony\Component\Console\Command\Command; use Magento\Framework\Exception\LocalizedException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ActiveUsersCommand extends Command { /** * {@inheritdoc} */ protected function configure() { $this->setName([modulename]:active_users') ->setDescription('Activate all users'); parent::configure(); } public function activateUsers() { /* do something here */ } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { try { $startTime = microtime(true); $this->activateUsers(); $resultTime = microtime(true) - $startTime; $output->writeln( 'All users have been activated successfully in ' . gmdate('H:i:s', $resultTime) ); } catch (LocalizedException $e) { $output->writeln($e->getMessage()); } catch (\Exception $e) { $output->writeln($e->getMessage()); } } }
- Try to run CLI command in console
<span style="font-weight: 400;">php bin/magento list</span>
Step 3: you will get the result
- You will get the below :
... [modulename] [modulename]:active_users Activate all users
<span style="font-weight: 400;">php bin/magento [modulename]:active_users</span>
- You will get the below :
All users have been activated successfully in 00:00:00
And the steps mentioned above explains how you Declare CLI Commands in Magento 2 Module. Replicate these steps to include as several options as required in the Magento 2 Module.
Leave a Reply