我正在尝试将一个新的up Model对象作为引用从Laravel Job传递给被调用的对象和方法。我需要在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();
}
}一切似乎都很正常。新的up对象被传递给SuperStoreScraper和父Scraper类(通过构造函数),但是当我在Scraper对象的start()方法中将其持久化到数据库时,它并没有反映到ScrapeJob (它更新了Scraper对象),然后在尝试更新持久化对象时,我在作业的failed()方法中得到一个错误。
ErrorException: Trying to get property of non-object in ...\app\Jobs\ScrapeJob.php:54这里我漏掉了什么?
发布于 2017-05-27 02:26:21
我想我现在已经解决了我的问题。
我已经将\应用\Scrape实例化移动到作业的__constructor,但也将其持久化到数据库中,如下所示:
protected $scrape;
public function __construct(Store $store)
{
$this->store = $store;
$this->scrape = \App\Scrape::create(['status' => 'queued']);
}这是可行的,我可以从Scraper和作业的()方法访问抓取模型,但是,如果我在作业上有多次尝试,我想为每次尝试创建新的抓取实例化。现在,每次作业重试都会更新相同的抓取实例(相同的id)。
https://stackoverflow.com/questions/44206771
复制相似问题