如何将参数发送到队列?

如何将参数发送到队列?

问题描述:

请考虑以下工作:

<?php

namespace App\Jobs;

use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImportUsers extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function __construct($number)
    {
        $this->number=$number;
    }

    public function handle()
    {
        dd($this->number);
        return;
    }
}

使用sync队列$this->dispatch(new \App\Jobs\ImportUsers(5));调度此作业会引发以下异常:Undefined property: App\Jobs\ImportUsers::$number.这对我来说真的很奇怪.为什么handle方法无法访问类属性?

Dispatching this job using a sync queue $this->dispatch(new \App\Jobs\ImportUsers(5)); throw this exception: Undefined property: App\Jobs\ImportUsers::$number. This really seems odd for me. Why the handle method can not access class properties?

正确声明您的财产

class ImportUsers extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $number; // <-- Here

    public function __construct($number)
    {
        $this->number=$number;
    }

    public function handle()
    {
        dd($this->number);
        return;
    }
}

在从队列中反序列化作业之后,您松开了动态创建的属性.

What happens is after the jobs is being deserialized from the queue you loose dynamically created property.

尝试一下:


$ php artisan tinker
>>> Bus::dispatch(new App\Jobs\ImportUsers(7));
7
>>>