artisan句柄函数控制台命令的返回值

ace*_*777 8 laravel laravel-8

我使用以下命令创建了一个 artisan 命令:

php artisan make:command --command=custom:command SomeCustomCommand
Run Code Online (Sandbox Code Playgroud)

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

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Kry*_*ach 8

尽管返回值不会影响 CLI 中的命令执行,但可以从命令handle()方法返回的整数值0, 1 or 2具有特定含义。

请看一下家长课。Illuminate\Console\Command在命令方法中返回整数值时,您可以在其中Symfony\Component\Console\Command\Command找到可以使用(并且在我看来应该使用)的公共常量handle()。它使您的命令在逻辑上完整。

public const SUCCESS = 0;
public const FAILURE = 1;
public const INVALID = 2;
Run Code Online (Sandbox Code Playgroud)

我通常会做类似的事情:

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $this->info('Send Toolkit Report Command');
        $this->info($this->description);
        $this->info('Processing...');

        try {
            $email = $this->argument('email');

            /** @var User|null $user */
            $user = User::query()->where('email', '=', $email)->first();

            if (!$user) {
                $warning = sprintf("User with given email '%s' does not exist", $email);
                $this->warn($warning);
                Log::warning(get_class($this));
                Log::warning($warning);

                return self::INVALID;
            }

            GenerateToolkitReport::dispatch($user);
        } catch (\Throwable $exception) {
            $this->error('Command failed with error:');
            $this->error($exception->getMessage());
            $this->error('Please check the logs!');
            Log::error($exception);

            return self::FAILURE;
        }

        $this->info('Toolkit Report generation has been dispatched to the queue.');
        $this->info('Successfully processed!');

        return self::SUCCESS;
    }
Run Code Online (Sandbox Code Playgroud)