跳到内容

了解控制台参数和选项的处理方式

编辑此页

Symfony 控制台应用程序遵循大多数 CLI 实用工具中使用的相同 docopt 标准。本文解释了当命令定义带有必需值、无值等的选项时,如何处理边缘情况。阅读另一篇文章,了解如何在 Symfony 控制台命令中使用参数和选项。

看看以下具有三个选项的命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace Acme\Console\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'demo:args', description: 'Describe args behaviors')]
class DemoArgsCommand extends Command
{
    protected function configure(): void
    {
        $this
            ->setDefinition(
                new InputDefinition([
                    new InputOption('foo', 'f'),
                    new InputOption('bar', 'b', InputOption::VALUE_REQUIRED),
                    new InputOption('cat', 'c', InputOption::VALUE_OPTIONAL),
                ])
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // ...
    }
}

由于 foo 选项不接受值,因此它将是 false(当它没有传递给命令时)或 true(当用户传递 --foo 时)。 bar 选项(及其 b 快捷方式)的值是必需的。它可以与选项名称用空格或 = 字符分隔。cat 选项(及其 c 快捷方式)的行为类似,只是它不需要值。查看下表以概述传递选项的可能方式

输入 foo bar cat
--bar=Hello false "Hello" null
--bar Hello false "Hello" null
-b=Hello false "=Hello" null
-b Hello false "Hello" null
-bHello false "Hello" null
-fcWorld -b Hello true "Hello" "World"
-cfWorld -b Hello false "Hello" "fWorld"
-cbWorld false null "bWorld"

当命令也接受可选参数时,情况会变得稍微复杂一些

1
2
3
4
5
6
// ...

new InputDefinition([
    // ...
    new InputArgument('arg', InputArgument::OPTIONAL),
]);

您可能必须使用特殊的 -- 分隔符来分隔选项和参数。查看下表中的第五个示例,其中使用它来告诉命令 Worldarg 的值,而不是可选的 cat 选项的值

输入 bar cat arg
--bar Hello "Hello" null null
--bar Hello World "Hello" null "World"
--bar "Hello World" "Hello World" null null
--bar Hello --cat World "Hello" "World" null
--bar Hello --cat -- World "Hello" null "World"
-b Hello -c World "Hello" "World" null
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本