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
.
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>
PHP
fileNow, 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;
}
}
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!