When working with Symfony console commands, we may want to support multiple names for a single command. This is useful when maintaining backward compatibility, migrating from older command names, or offering more intuitive alternatives for internal tools. Symfony allows us to define command aliases in more than one way. This tutorial provides 2 methods how to define console command alias in Symfony 8 application.
Method 1 - 'AsCommand' attribute with 'aliases'
The AsCommand attribute offers a clean and modern way to configure console commands. Besides defining the main command name, it also allows us to specify one or more aliases via the aliases option. By doing this, we can execute the same command using different names without duplicating any logic.
src/Command/TestCommand.php
<?php
namespace App\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;
#[AsCommand(name: 'app:test', aliases: ['project:test', 'app:old-name'])]
class TestCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln($this->getAliases());
return self::SUCCESS;
}
}
Method 2 - Pipe seperator
Another option is to declare aliases directly within the command name itself. Symfony supports using a pipe (|) character to separate multiple command names in the AsCommand attribute. The first name listed becomes the main name, and the remaining ones are registered as aliases.
src/Command/TestCommand.php
<?php
namespace App\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;
#[AsCommand(name: 'app:test|project:test|app:old-name')]
class TestCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln($this->getAliases());
return self::SUCCESS;
}
}
Leave a Comment
Cancel reply