在命令行上运行 Laravel 任务时如何传递多个参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14394597/
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
How to pass multiple arguments when running Laravel Tasks on command line?
提问by did1k
I created a Task class with method that needs multiple arguments:
我用需要多个参数的方法创建了一个 Task 类:
class Sample_Task
{
public function create($arg1, $arg2) {
// something here
}
}
But it seems that artisan only gets the first argument:
但似乎工匠只得到第一个参数:
php artisan sample:create arg1 arg2
Error message:
错误信息:
Warning: Missing argument 2 for Sample_Task::create()
How to pass multiple arguments in this method?
如何在此方法中传递多个参数?
采纳答案by ray
class Sample_Task
{
public function create($args) {
$arg1 = $args[0];
$arg2 = $args[1];
// something here
}
}
回答by William Turrell
Laravel 5.2
Laravel 5.2
What you need to do is specify the argument (or option, e.g. --option) in the $signature
property as an array. Laravel indicates this with an asterisk.
您需要做的是将$signature
属性中的参数(或选项,例如 --option)指定为数组。Laravel 用星号表示这一点。
Arguments
参数
e.g. supposing you have an Artisan command to "process" images:
例如,假设您有一个 Artisan 命令来“处理”图像:
protected $signature = 'image:process {id*}';
If you then do:
如果你这样做:
php artisan help image:process
…Laravel will take care of adding the correct Unix-style syntax:
…Laravel 会负责添加正确的 Unix 风格的语法:
Usage:
image:process <id> (<id>)...
To access the list, in the handle()
method, simply use:
要访问列表,在handle()
方法中,只需使用:
$arguments = $this->argument('id');
foreach($arguments as $arg) {
...
}
Options
选项
I said it worked for options too, you use {--id=*}
in $signature
instead.
我说它也适用于选项,你用{--id=*}
in$signature
代替。
The help text will show:
帮助文本将显示:
Usage:
image:process [options]
Options:
--id[=ID] (multiple values allowed)
-h, --help Display this help message
...
So the user would type:
所以用户会输入:
php artisan image:process --id=1 --id=2 --id=3
And to access the data in handle()
, you'd use:
要访问 中的数据handle()
,您可以使用:
$ids = $this->option('id');
If you omit 'id', you'll get alloptions, including booleans for 'quiet','verbose' etc.
如果省略 'id',您将获得所有选项,包括用于 'quiet'、'verbose' 等的布尔值。
$options = $this->option();
You may access the list of IDs in $options['id']
您可以访问 ID 列表 $options['id']
More info in the Laravel Artisan guide.
Laravel 工匠指南中的更多信息。