【问题标题】:How to pass multiple arguments when running Laravel Tasks on command line?在命令行上运行 Laravel 任务时如何传递多个参数?
【发布时间】:2016-08-20 22:46:24
【问题描述】:

我用需要多个参数的方法创建了一个 Task 类:

class Sample_Task
{
    public function create($arg1, $arg2) {
        // something here
    }
}

但似乎工匠只得到第一个参数:

php artisan sample:create arg1 arg2

错误信息:

Warning: Missing argument 2 for Sample_Task::create()

如何在这个方法中传递多个参数?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    Laravel 5.2

    您需要做的是将$signature 属性中的参数(或选项,例如--option)指定为数组。 Laravel 用星号表示。

    参数

    例如假设您有一个 Artisan 命令来“处理”图像:

    protected $signature = 'image:process {id*}';
    

    如果你这样做:

    php artisan help image:process
    

    ...Laravel 将负责添加正确的 Unix 样式语法:

    Usage:
      image:process <id> (<id>)...
    

    要访问列表,在handle() 方法中,只需使用:

    $arguments = $this->argument('id');
    
    foreach($arguments as $arg) {
       ...
    }
    

    选项

    我说过它也适用于选项,您可以在 $signature 中使用 {--id=*}

    帮助文本将显示:

    Usage:
      image:process [options]
    
    Options:
          --id[=ID]         (multiple values allowed)
      -h, --help            Display this help message
    
      ...
    

    所以用户会输入:

    php artisan image:process --id=1 --id=2 --id=3
    

    要访问handle() 中的数据,您可以使用:

    $ids = $this->option('id');
    

    如果省略“id”,您将获得所有选项,包括“安静”、“详细”等布尔值。

    $options = $this->option();
    

    您可以访问$options['id']中的ID列表

    更多信息请关注Laravel Artisan guide

    【讨论】:

      【解决方案2】:
      class Sample_Task
      {
          public function create($args) {
             $arg1 = $args[0];
             $arg2 = $args[1];
              // something here
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 2010-10-23
        • 2019-08-28
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        相关资源
        最近更新 更多