Laravel 任意设置退出状态代码到自定义命令

Dim*_*las 5 php command-line-interface laravel laravel-5.7

我正在实现以下自定义命令来运行后台进程:

namespace App\Console\Commands;

use App\Model\MyModel;
use Exception;
use Illuminate\Console\Command;

class MyCommand extends Command
{
    /**
     * @var string
     */
    protected $description = "Doing StuffyStuff";

    /**
     * @var string
     */
    protected $signature = "mycommand:dostuff";

    public function __construct()
    {
        parent::__construct();
    }

    public function handle(MyModel $model): void
    {
        //@todo Implement Upload
        try {
            $model->findOrFail(12);
            //Set Exit Status Code 0
        } catch (Exception $e) {
            //Set status code 1
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我想根据是否抛出异常来指定状态代码。如果成功,我想使用退出状态代码 0,如果失败,我想使用 Unix 规范指定的退出状态代码 1。

那么你有什么想法如何做到这一点吗?

Ela*_*lad 9

您可以在任何地方返回代码

public function handle(MyModel $model): int
    {
        //@todo Implement Upload
        try {
            $model->findOrFail(12);
            return 0;
        } catch (Exception $e) {
            $this->error($e->getMessage());
            return 1;
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看示例并进行解释

  • 最好使用 `Command::SUCCESS` (0) 或 `Command::FAILURE` (1) 等常量,而不是“魔法”数字。 (7认同)