Creare un command su Symfony 6
Symfony 6 ha dei comandi preimpostati usando lo script bin/console. Per creare un command su Symfony dobbiamo:
- estendere la classe Command (dove sono definiti tutti i comandi);
- specificare il nome del comando: in questo caso lo chiamiamo landofworld:test
- usiamo la funzione protetta configure() per definire un argomento richiesto o opzionale oppure definire una descrizione :
<?php
namespace Landofworld\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Container;
#[AsCommand(
name: 'landofworld:test',
description: 'Land of World Test',
hidden: false
)]
class LandofwordTestCommand extends Command
{
public function __construct(Container $container)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('name', InputArgument::REQUIRED, 'Ciao, inserisci il tuo nome!');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
if ($input->getArgument('name') != null) {
$output->writeln("<info>Ciao " . $input->getArgument('name') . ", benvenuto su Land of World!</info>");
return Command::SUCCESS;
}
$output->writeln("<info>Ops! Qualcosa è andato storto...</info>");
return Command::FAILURE;
}
}
Una volta pronta la classe PHP e la parte procedurale della funzione protetta execute(), occorre registrare il comando al servizio (ad esempio services.yaml):
Landofworld\Command\LandofworldTestCommand:
public: false
arguments: [ '@service_container' ]
Per eseguire il comando sarà necessario scrivere nel terminale:
bin/console landofworld:test