Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ShouldQueue How Does It Work

Tags:

php

laravel

I know how to use ShouldQueue my question is about why does it work the way it does.

I need to edit how my new Job is stored in the database, and therefore am digging through Laravel's internals.

The job I want to edit is launched from the following event listener:

<?php

namespace App\Listeners;

use App\Events\NewMail;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Jobs\SendEmail;
use Carbon\Carbon;
class NewMailListener implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NewMail  $event
     * @return void
     */
    public function handle(NewMail $event)
    {
       $addressee = $event->user->name;
       $address = $event->user->email;
       $type = "NewMail";
       $job = (new SendEmail($type,$addressee,$address))->delay(Carbon::now()->addMinutes(10));
       dispatch($job);
    } 
}

What I don't understand is how the ShouldQueue magic works, because in the source code it appears to do nothing.

<?php

namespace Illuminate\Contracts\Queue;

interface ShouldQueue
{
    //
}

I understand it is a contract but it's not defining anything... so what it is doing exactly? Is there some auto-loading happening from the namespace?

I wasn't sure what an interface was exactly, so I looked at this: PHP Docs: Interfaces and came away with the impression that even if it is for decoupling, and interface should be defining something, which I don't see in ShouldQueue.

The top comment on that PHP docs page says this:

An INTERFACE is provided so you can describe a set of functions and then hide the final implementation of those functions in an implementing class. This allows you to change the IMPLEMENTATION of those functions without changing how you use it.

But where is this description of functions here?

PS - I know this interface/contract is being used to queue the event listener itself, not the job that I want to edit. But I'm hoping understanding how the queue interacts with the event listener will better inform me as to how it works for the jobs.

like image 635
Summer Developer Avatar asked Jan 21 '18 18:01

Summer Developer


1 Answers

Internally Laravel checks if Job or Mailable or Notification etc implements ShouldQueue interface. For example:

if ($job instanceof ShouldQueue) {

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Console/Scheduling/Schedule.php#L86

like image 145
Alexey Mezenin Avatar answered Sep 25 '22 14:09

Alexey Mezenin