在 Laravel 中向作业添加参数后失败

Fail after adding parameters to job in Laravel

我以前写的一个没有参数的作业现在需要它们。它旨在使用 Mail class 发送电子邮件。我现在需要使用参数执行此作业,但队列没有看到它们。

我想知道我是否以错误的方式初始化 SendMailFinished,但应该没问题。

我了解到序列化存在问题,但我在 SendMailFinished 中添加了受保护的变量。

class ReporteBCH implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     * No hay que pasar ninguna variable.
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Busca todos los equipos del inventario, luego revisa el SCCM con sus relaciones y el bginfo
     *
     * @return void
     */
    public function handle()
    {
        $msg = 'Proceso terminado. Ver ' . url('');
        $subj = 'Proceso BCH';
        $mailto = env('MAIL_TO');
        $send = new SendMailFinished($msg, $subj, $mailto);
        $send->dispatch();
    }


}

现在问题是当我从控制台启动它时进程失败了,因为它看不到参数,就好像我没有在构造函数中添加它们一样。

SendMailFinished 看起来像这样:

class SendMailFinished implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public $tries = 3;

    protected $msg;

    protected $subj;

    protected $mailto;


    public function __construct($msg, $subj, $mailto)
    {
        //
        $this->msg = $msg;
        $this->subj = $subj;
        $this->mailto = $mailto;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //Envia correo cuando termine cola.
        Mail::to($this->mailto)->queue(new TasksFinished($this->msg, $this->subj));
    }
}

错误如下:

Symfony\Component\Debug\Exception\FatalThrowableError: Too few arguments to function App\Jobs\SendMailFinished::__construct(), 0 passed in C:\laragon\www\reportes\vendor\laravel\framework\src\Illuminate\Foundation\Bus\Dispatchable.php on line 26 and exactly 3 expected in C:\laragon\www\reportes\app\Jobs\SendMailFinished.php:31

我读过https://laravel.com/docs/5.8/queues#creating-jobs but there's not much to learn about it and also this one

如何调用命令非常重要。问题是,当您在构造函数中定义变量时,您的命令需要一些数据。如果您在没有该数据的情况下调用您的命令,构造函数将不会获得任何数据,并且您将得到一个异常。

首先,您需要更改您的命令签名,以期待一些参数(如果您还没有):

protected $signature = 'your:command {msg}{subject}{mailTo}'

稍后,当您调用命令时,您需要传递所有这些参数:

php artisan your:command parameter1 parameter2 parameter3

在官方 documentation 阅读更多内容。

好吧,最后的答案是不能像正常 class 那样传递参数,而是必须一次性将它们添加到调度中 class。

这不起作用:

$send = new SendMailFinished($msg, $subj, $mailto);
        $send->dispatch();

这个有效:

SendMailFinished::dispatch($msg, $subj, $mailto);

在 Laravel 个问题中找到了一个 explanation