Home Blog Contact

How to create a command in Shopware 6?

Jan 25th 2022

Commands are great so you can execute code from the command line. Today we will create our own custom command. Firstly, you need to have a plugin, if you are not sure how to create one, please check this tutorial. My plugin name is MatheusGontijoHelloWorld.


Register command in services.xml

Within your plugin directory, go to file src/Resources/config/services.xml. Please add the following code:

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

Create the PHP file

Now, add the PHP file to src/Command/HelloWorldCommand.php. Make sure you always end the command files with the suffix Command, otherwise it won't work. Please add the following code:

<?php declare(strict_types=1);

namespace MatheusGontijo\HelloWorld\Command;

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

class HelloWorldCommand extends Command
{
    protected static $defaultName = 'matheus-gontijo:hello-world';

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('Let\'s see if it works!');
        return self::SUCCESS;
    }
}

Run command

Let's run the custom command on command line:

php bin/console matheus-gontijo:hello-world

Result:

Let's see if it works!

Great! Now we have a custom command! Hope you liked it - have a good one!