vendredi 26 mai 2017

Send through object reference from Laravel Job (simple OOP?)

I'm trying to pass a newed up Model Object as a reference from a Laravel Job to the called Object and method. I need to new up the particular model in the Job because I need it in the Job's failed() method to update that model (and persist to database) as it functions as a log.

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

Everything seems to work fine. The newed up object is passed to both the SuperStoreScraper and the parent Scraper class (through the constructor), BUT when I persist it to the database in the Scraper object start() method, it doesn't reflect that up to the ScrapeJob (which newed up the Scrape object) and then I get an error in the Job's failed() method when trying to update the persisted object.

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

What am I missing here?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2qnWGRc
via IFTTT

Aucun commentaire:

Enregistrer un commentaire