How to Add New Console Command in Magento 2

How To Add New Console Command In Magento 2

Create a new module with CustomCommandLine_ConsoleCommand.

Step 1: Create registration.php file.

app/code/CustomCommandLine/ConsoleCommand/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
	\Magento\Framework\Component\ComponentRegistrar::MODULE,
	'CustomCommandLine_ConsoleCommand',
	__DIR__
);

Step 2: Create module.xml file.

app/code/CustomCommandLine/ConsoleCommand/etc/module.xml

<?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="CustomCommandLine_ConsoleCommand" setup_version="1.0.0">
    </module>
</config>

Step 3: Create di.xml file.

app/code/CustomCommandLine/ConsoleCommand/etc/di.xml

<?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_generation" xsi:type="object">CustomCommandLine\ConsoleCommand\Model\Generation</item>
            </argument>
        </arguments>
    </type>
</config>

Step 4: Create Generation.php file.

app/code/CustomCommandLine/ConsoleCommand/Model/Generation.php

<?php

namespace CustomCommandLine\ConsoleCommand\Model;

use \Symfony\Component\Console\Command\Command;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Output\OutputInterface;
class Generation extends Command
{
    protected function configure()
    {
        $this->setName('generation:clean')->setDescription('Clean Generation Folder');
        parent::configure();
    }
    protected function execute(InputInterface $input, OutputInterface $output)
{   
        system("rm -r generated/*");
        $output->writeln('Generation Folder Clean Successfully.');
    }
}

Step 5: Next, we need to check if your new command is shown in the command list or not for that you need to run the following command.

php bin/magento

Step 6: Lastly, you need to execute the command.

php bin/magento generation:clean

Please contact us at manish@bay20.com or call us at +91-8800519180 for any support related to Magento 2. You can also visit the Magento2 development page to check the services we offer.