首页 > 解决方案 > 缺少控制台命令参数时显示问题

问题描述

我正在 Symfony 中编写控制台命令。

当用户没有指定名称参数时,我不明白是否可以显示我添加的问题(你想问候谁?)。

class GreetCommand extends Command
{
    // ...

    protected function configure()
    {
        $this
            ->setName('greet:someone')
            ->setDescription('Greet somebody')
            ->addArgument('name', InputArgument::REQUIRED, 'Who do you want to greet?')
        ;
    }
}
protected function execute(InputInterface $input, OutputInterface $output)
{
    $year = $input->getArgument('name');
...

目前,如果我运行bin/console greet:someone命令,我会收到以下错误:

没有足够的参数(缺少:“名称”)。
问候某人

标签: symfony

解决方案


Symfony Style 对象可以帮助你做到这一点。

首先将您的参数更改为可选而不是必需。

protected function configure()
{
    $this
        ->setName('greet:someone')
        ->setDescription('Greet somebody')
        ->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?')
    ;
}

然后你可以使用 SymfonyStyle 对象来帮助你交互式地问问题:

// Use this method to instantiate a SymfonyStyle
protected function initialize(InputInterface $input, OutputInterface $output)
{
    $this->io = new SymfonyStyle($input, $output);
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $name = $input->getArgument('name');
    if (!$name) {
        $name = $this->io->ask('Who do you want to greet?');
    }
...

ask 方法采用第二个参数为 name 提供默认值,并采用第三个参数来验证用户输入是否具有可调用性。它们都是可选的。

https://symfony.com/doc/current/console/style.html#user-input-methods


推荐阅读