Easy way to Create Custom command in Magento 2

Posted by

In situations demanding swift actions, such as merging two commands seamlessly, Magento 2 offers a solution to create a custom command. Crafting your custom command becomes essential when default Magento commands fall short. Whether you need to execute unique code sets or streamline specific tasks, a custom command tailored to your requirements proves invaluable in meeting your needs efficiently and effectively.

Module for Custom command

If you know how to create a custom module then you can skip this section and move on to next one. To create a custom module you need 3 files, module.xml, registration.php and composer.json file where composer.json is an optional. You can follow our article on creating a custom module.

Create or edit di.xml file

Create the below file under you custom module. app/code/<company name>/<module name>/etc/di.xml. Note that although the command will be executed via the CLI, the file should reside in the etc directory, not etc/adminhtml. The significance of this file is elaborated in our article titled “Purpose of di.xml file.” For a deeper understanding of the di.xml file, refer to the detailed insights provided in the mentioned article.

Within the di.xml file, leverage the type element with the name Magento\Framework\Console\CommandList to precisely define the command option. This strategic use of the type element facilitates seamless customization of the command within the file configuration.

<?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="combine_command" xsi:type="object">Learningmagento\Customcommand\Console\CombineCommand</item>
           </argument>
       </arguments>
   </type>
</config>

In this example we will create a custom command which will combine 3 commands into 1 which are setup:upgrade, di:compile and content-deploy.

Create a class for the custom command

In this configuration, the declaration of the command class “CombineCommand” takes center stage. Within this class, the intricacies of the command, including its name and the execution logic encapsulated in the execute() method, are precisely defined. This thoughtful design in the configuration ensures clarity and effectiveness in implementing the desired command functionality.

<?php

/**
 *
 * @category  Custom Development
 * @email     contactus@learningmagento.com
 * @author    Learning Magento
 * @website   learningmagento.com
 * @Date      20-01-2024
 */
namespace Learningmagento\Customcommand\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CombineCommand extends Command
{
    protected function configure()
    {
        $this->setName('combined:commands');
        $this->setDescription('Run all main 3 commands of Magento which are setup:upgrade, di:compile and content deploy');
        parent::configure();
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $commandList = array('setup:upgrade', 'setup:di:compile', 'setup:static-content:deploy -f');
        foreach ($commandList as $list) {
            $command = $this->getApplication()->find($list);
            $returnCode = $command->run($input, $output);
            if(!$returnCode) {
                $output->writeln($list . ' successfully finished');
            }
        }
    }
}

There are two functions in the above class which are important while building a custom command. These are configure() and execute().

configure()

This function plays a pivotal role in configuring the name, description, and command-line arguments for the Magento 2 added command. Its purpose is to effectively define essential details, ensuring a well-structured and informative command-line interface.

When you run php bin/magento or php bin/magento list it will show all the command list and its details. Here it will show the name and description which we defined in our function.

execute()

True to its name, this function springs into action upon entering the command and pressing enter. Representing the command’s core, the execute() function dictates the sequence of operations. In our scenario, it orchestrates the sequential execution of three commands: setup:upgrade, setup:di:compile, and setup:static-content:deploy -f, ensuring a cohesive and efficient flow of tasks.

Conclusion

In the conclusion for creating a custom command in Magento 2, You can create any such commands which you want in our case we created one command which will ran 3 commands making easier for installing a new module. Same way you can create a cache flush and cache clear command or you can create a command which is specify to your custom module like turning on and off configuration settings.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *