Laravel 命令 - 仅可选参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46670304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel command - Only optional argument
提问by TheNiceGuy
I have a command with this signature
我有一个带有这个签名的命令
order:check {--order}
And execute this:
并执行这个:
php artisan order:check --order 7
For some reason that results in this exception
由于某种原因导致此异常
[RuntimeException]
Too many arguments, expected arguments "command".
Why? I want that this command can either be executed as php artisan order:check
or with an optional order id php artisan order:check --order X
为什么?我希望此命令可以作为php artisan order:check
或使用可选的订单 ID 执行php artisan order:check --order X
回答by Cy Rossignol
The {--order}
option (without an =
sign) declares a switchoption, which takes no arguments. If the switch option is present, its value equals true
, and, when absent, false
(--help
is like a switch—no argument needed).
的{--order}
选项(无=
符号)声明了一个开关选项,这需要没有参数。如果存在 switch 选项,则其值等于true
,并且,如果不存在,false
(--help
就像一个开关——不需要参数)。
When we provide an argument on the command line for this option, the console framework cannot match the input to an option with an argument, so it throws the error as shown in the question.
当我们在命令行上为此选项提供参数时,控制台框架无法将输入与带有参数的选项匹配,因此它会抛出问题中所示的错误。
To allow the option to accept an argument, change the command's $signature
to:
要允许选项接受参数,请将命令更改$signature
为:
protected $signature = 'order:check {--order=}'
Note the addition of the equal sign after --order
. This tells the framework that the --order
option requiresan argument—the command will throw an exception if the user doesn't provide one.
请注意在 之后添加等号--order
。这告诉框架该--order
选项需要一个参数——如果用户不提供参数,该命令将抛出异常。
If we want our command to accept an option with or withoutan argument, we can use a similar syntax to provide a default value:
如果我们希望我们的命令接受带或不带参数的选项,我们可以使用类似的语法来提供默认值:
protected $signature = 'order:check {--order=7}'
...but this doesn't seem useful for this particular case.
...但这对于这种特殊情况似乎没有用。
After we set this up, we can call the command, passing an argument for --order
. The framework supports both formats:
设置好之后,我们可以调用命令,为 传递一个参数--order
。该框架支持两种格式:
$ php artisan order:check --order=7
$ php artisan order:check --order 7
...and then use the value of order
in our command:
...然后order
在我们的命令中使用的值:
$orderNumber = $this->option('order'); // 7