You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel自定义Artisan命令中向handle()传递指定参数?

Laravel自定义Artisan命令添加参数实现方案

要实现传递places或lounges参数,你需要通过修改命令签名定义参数,再在执行方法中获取并使用参数,具体步骤如下:

1. 修改命令签名($signature)

在$signature中添加必填参数{type},同时补充参数说明,让命令的帮助信息更清晰:

protected $signature = 'app:update-places-images {type : 指定要更新的类型,可选值为places或lounges}';

2. 在handle()方法中获取并使用参数

通过$this->argument('type')获取传递的参数值,然后根据值判断调用对应的更新方法,同时增加参数合法性校验:

public function handle()
{
    $type = $this->argument('type');

    // 校验参数是否合法
    if (!in_array($type, ['places', 'lounges'])) {
        $this->error('无效参数!请使用places或lounges作为参数');
        return 1; // 返回非0状态码标记命令执行失败
    }

    if ($type === 'places') {
        $this->updatePlacesImages();
        $this->info('Places数据更新完成');
    } else {
        $this->updateLoungesImages();
        $this->info('Lounges数据更新完成');
    }
}

完整修改后的代码

class UpdatePlacesImages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:update-places-images {type : 指定要更新的类型,可选值为places或lounges}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '从Places API获取地点数据(尤其是图片)并保存到goog_data字段';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $type = $this->argument('type');

        if (!in_array($type, ['places', 'lounges'])) {
            $this->error('无效参数!请使用places或lounges作为参数');
            return 1;
        }

        if ($type === 'places') {
            $this->updatePlacesImages();
            $this->info('Places数据更新完成');
        } else {
            $this->updateLoungesImages();
            $this->info('Lounges数据更新完成');
        }
    }

    // 你的updatePlacesImages()实现逻辑
    protected function updatePlacesImages()
    {
        // 原有业务代码
    }

    // 你的updateLoungesImages()实现逻辑
    protected function updateLoungesImages()
    {
        // 原有业务代码
    }
}

运行命令示例

  • 更新places数据:
php artisan app:update-places-images places
  • 更新lounges数据:
php artisan app:update-places-images lounges

可选扩展:支持无参数默认更新全部

如果需要让参数变为可选(不传递参数时默认更新两者),可以修改签名为可选参数:

protected $signature = 'app:update-places-images {type? : 指定要更新的类型,可选值为places或lounges,默认更新两者}';

然后在handle方法中处理默认情况:

public function handle()
{
    $type = $this->argument('type');

    if (is_null($type)) {
        $this->updatePlacesImages();
        $this->updateLoungesImages();
        $this->info('所有数据更新完成');
        return;
    }

    // 原有参数校验及分支逻辑
}

内容的提问来源于stack exchange,提问作者Malik Muhammad Awan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:32:44