更改默认命令
当没有传递命令名称时,Console 组件将始终运行 ListCommand
。为了更改默认命令,你需要将命令名称传递给 setDefaultCommand()
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
namespace Acme\Console\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: 'hello:world')]
class HelloWorldCommand extends Command
{
protected function configure(): void
{
$this->setDescription('Outputs "Hello World"');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('Hello World');
return Command::SUCCESS;
}
}
执行应用程序并更改默认命令
1 2 3 4 5 6 7 8 9
// application.php
use Acme\Console\Command\HelloWorldCommand;
use Symfony\Component\Console\Application;
$command = new HelloWorldCommand();
$application = new Application();
$application->add($command);
$application->setDefaultCommand($command->getName());
$application->run();
通过运行以下命令来测试新的默认控制台命令
1
$ php application.php
这将在命令行打印以下内容
1
Hello World
警告
此功能有一个限制:你不能向默认命令传递任何参数或选项,因为它们会被忽略。
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。