首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Laravel Job发送对象引用(简单的OOP?)

从Laravel Job发送对象引用(简单的OOP?)
EN

Stack Overflow用户
提问于 2017-05-27 01:02:28
回答 1查看 581关注 0票数 0

我正在尝试将一个新的up Model对象作为引用从Laravel Job传递给被调用的对象和方法。我需要在Job中新建特定的模型,因为我需要在Job的failed()方法中更新该模型(并持久化到数据库中),因为它起到了日志的作用。

代码语言:javascript
复制
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();
    }
}

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

代码语言:javascript
复制
ErrorException: Trying to get property of non-object in ...\app\Jobs\ScrapeJob.php:54

这里我漏掉了什么?

EN

回答 1

Stack Overflow用户

发布于 2017-05-27 02:26:21

我想我现在已经解决了我的问题。

我已经将\应用\Scrape实例化移动到作业的__constructor,但也将其持久化到数据库中,如下所示:

代码语言:javascript
复制
protected $scrape;

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

这是可行的,我可以从Scraper和作业的()方法访问抓取模型,但是,如果我在作业上有多次尝试,我想为每次尝试创建新的抓取实例化。现在,每次作业重试都会更新相同的抓取实例(相同的id)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44206771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档