如何将参数发送到队列?

时间:2015-09-30 03:32:18

标签: php laravel queue laravel-5.1

请考虑以下工作:

<?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方法无法访问类属性?

1 个答案:

答案 0 :(得分:10)

正确声明您的财产

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;
    }
}

在从队列中反序列化作业后,您将动态创建属性。

试一试:

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