Magento 2 create custom command

Magento 2 create custom command

Today we discuss how in Magento 2 create custom command. Sometime we need to import sample data or use the long queries to get data so for that it is better to use command line interface. Magento 2 use mostly command line interface for upgrade, reindex, static content deploy and many other command available. Here is list of default magento available command. So let’s start with our custom command.

Step 1: Define Command

For custom command keep in mind in item name qaisarSatti_helloworld first letter will your nameSpace. Now add following code to your di.xml

<?xml version="1.0"?>

<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
            <argument name="commands" xsi:type="array">
                <item name="qaisarSatti_helloworld" xsi:type="object">QaisarSatti\HelloWorld\Console\Command\HelloWorld</item>

Step 1: Create Command

Now Create file HelloWorld.php in following directory.


In your configure method just set

setName(‘qaisarsatti:helloworld’) // this will be your command that you run from cli
setDescription(‘Command Description’) // add your command detail

In you execute method you add your custom logic


namespace QaisarSatti\HelloWorld\Console\Command;

use \Symfony\Component\Console\Command\Command;
use \Symfony\Component\Console\Input\InputInterface;
use \Symfony\Component\Console\Output\OutputInterface;

class HelloWorld extends Command

    public function __construct(
    ) {

    protected function configure()
            ->setDescription('Just Checking for command'); //add you description here


    protected function execute(InputInterface $input, OutputInterface $output)
    //add your logic here
            $output->writeln('<info>Yahoooo command Successfully working!</info>');
        } catch (\Exception $e) {

Now check our command is listed or not. Just run following command

php bin/magento list

  qaisarsatti:helloworld                   Just Checking for command
command list

Now we execute the our command

php bin/magento qaisarsatti:helloworld

The output will be shown

Yahoooo command Successfully working!
run command

Now following this you can add new custom command in magento 2.


Recent Blogs





Leave a Reply