【问题标题】:Return value of artisan handle function console command工匠句柄函数控制台命令的返回值
【发布时间】:2021-05-06 09:21:13
【问题描述】:

我使用这个命令创建了一个工匠命令:

php artisan make:command --command=custom:command SomeCustomCommand

在我运行命令后,它创建了以下文件:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SomeCustomCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'custom:command';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        return 0;
    }
}

我注意到默认情况下handle 方法返回一个int。这是否意味着什么?如果我返回0 这意味着错误然后1 如果成功?我正在浏览 laravel 文档,它没有解释 handle 函数的返回值。

【问题讨论】:

    标签: laravel laravel-8


    【解决方案1】:

    你可以在那里返回任何你喜欢的东西,这取决于你从哪里/从哪里调用它,我见过人们在那里返回一个布尔值以及数据甚至什么都没有。

    我认为这更像是一个基于意见的主题。就个人而言,我返回一个布尔值,因为它适合我在项目中使用它们的用途,因为我使用实时通知来处理命令句柄失败/异常

    例如,如果您要使用 Artisan::call() 通过另一个类调用命令,您可以根据命令已完成的操作来决定运行逻辑(这可用于检查退出代码)。或者您可以捕获任何异常并处理它们。您无需在控制台命令中从 handle() 返回即可。

        try {
            Artisan::call($object->command);
        } catch (ArtisanCommandException $e) {
            Log::error($e);
        }
    
        //note ArtisanCommandException is custom
    

    见:https://laravel.com/docs/8.x/artisan#programmatically-executing-commands

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-21
      • 2016-03-15
      • 2016-10-05
      • 2017-12-24
      • 2021-12-31
      • 2021-09-15
      • 2021-05-15
      • 1970-01-01
      相关资源
      最近更新 更多