How to Create a CLI Command in Shopware 6?

How to create a command in Shopware6?

Commands are useful because they allow you to run code from the command line. There are many commands in shopware 6 that make your development easy. You can see the whole list of commands here.
Shopware has given such a service by which you can create your own custom CLI command for shopware 6.
We're going to help you make your own custom command today. To begin, you'll need a plugin. if you're not sure how to make one, check out this guide.

MageSparkHelloWorld is the name of my plugin.


In services.xml, add a command

Go to the file src/Resources/config/services.xml in your plugin directory. Please add the following code to your page:

services.xml

<service id="MageSpark\HelloWorld\Command\HelloWorldCommand">
    <tag name="console.command" />
</service>

Make the PHP file

Insert the PHP file into src/Command/HelloWorldCommand.php. Please add the following code in to the file.

HelloWorldCommand.php

<?php declare(strict_types=1);

namespace MageSpark\HelloWorld\Command;

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

class HelloWorldCommand extends Command{

    // Command: it will be used in CLI
    protected static $defaultName = 'mage-spark:work';

    protected function configure()
    {
        $this->setDescription("Simply Prints It Works in CLI");
    }

    // Functional logic for the command
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("It works!");

        return self::SUCCESS;
    }
}

Execute command

Let's use the command line to execute the custom command:

bin/console mage-spark:work

How to create a Command In Showare 6

Here, we are done creating a custom command for you! Hope this blog added value to your knowledge!

Have a wonderful day! And don’t forget to share your thoughts below!

Have fun coding!!

Starting your own Shopware6 Store?

Get Free Recommendations on Do's and Don'ts!

Talk to Experts
Talk to a Hyvä expert
Loading...