通过Laravel Job的对象引用发送(简单的OOP?)

时间:2017-05-26 17:02:28

标签: php laravel oop laravel-5

我试图将一个新建的模型对象作为Laravel Job的引用传递给被调用的Object和方法。我需要在Job中新建特定的模型,因为我需要在Job的failed()方法中更新该模型(并保留到数据库),因为它充当了日志。

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

    protected $store;
    protected $scrape;

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

    public function handle()
    {
        $this->scrape = new \App\Scrape; // This is the log object.

        // Here I call the SuperStoreScraper
        $class = '\App\Scraper\\' . $this->store->scraper;
        (new $class($this->store, $this->scrape))->scrape();
    }

    public function failed(\Exception $e)
    {
        // Update the Scrape object and persist to database.
        $data = $this->scrape->data; // here I get the error... ->data is not found?
        $data['exception'] = [ // this should work since I'm casting data to an array in the Model class.
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ];
        $this->scrape->data = $data;
        $this->scrape->status = 'failed';
        $this->scrape->save();
    }
}

class SuperStoreScraper extends Scraper
{
    public function __construct(Store $store, Scrape &$scrape) {
        parent::__construct($store, $scrape);
    }

    public function scrape() {
        $this->start();
    }
}

abstract class Scraper
{    
    protected $store;
    protected $scrape;

    public function __construct(Store $store, Scrape &$scrape) {
        $this->store = $store;
        $this->scrape = &$scrape;
    }

    protected function start()
    {
        $this->scrape->fill([
            'data' => [
                'store' => $this->store->name,
                'scraper' => $this->store->scraper
            ],
            'status' => 'scraping'
        ])->save();
    }
}

一切似乎都很好。新建的对象被传递给SuperStoreScraper和父Scraper类(通过构造函数),但是当我在Scraper对象的start()方法中将它持久化到数据库时,它并没有反映到ScrapeJob (它创建了Scrape对象)然后在尝试更新持久化对象时,在Job的failed()方法中出现错误。

ErrorException: Trying to get property of non-object in ...\app\Jobs\ScrapeJob.php:54

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

我想现在有点解决了我的问题。

我已将\ App \ Scrape实例移动到Job的__constructor,但也将其保存到数据库,如下所示:

protected $scrape;

public function __construct(Store $store)
{
    $this->store = $store;
    $this->scrape = \App\Scrape::create(['status' => 'queued']);
}

这很有效,我可以从Scraper和Job的failed()方法访问Scrape模型, BUT ,如果我在Job上有多次尝试我想创建新的Scrape实例每次尝试。现在,每个Job重试都会更新相同的Scrape实例(相同的id)。