0

I know you can listen to job events using before, after and failing hooks:

https://laravel.com/docs/5.6/queues#job-events

Queue::before(function (JobProcessing $event) {
    // $event->connectionName
    // $event->job
    // $event->job->payload()
});

I only want certain jobs to be picked up here though. These jobs are the ones that extend from a certain abstract base class called AbstractTask. Normally I would simply perform an instanceof check but something like this won't work:

$job instanceof AbstractTask

Is there any way I can mark a job to be picked up by these Job Events?

Edit

It seems the actual Job that I want(which is my very own Job class) can be found within the $event->job like so:

$payload = json_decode($job->getRawBody());
$data = unserialize($payload->data->command);

if ($data instanceof AbstractTask) {
    dd($data);
}

I find it hard to believe that there is not an easier way to fetch the underlying Job which actually is being processed so I made a Github issue as well:

https://github.com/laravel/framework/issues/25189

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
  • Why won't using `instanceof` work? – fubar Aug 12 '18 at 22:40
  • Since you can't instantiate an abstract class, one way to go around would be checking if your object implements certain method from your abstract class. That isn't however giving you certainty that the abstract class is inherited. Mabe you could provide more details on why you need to make this distinction? – alariva Aug 12 '18 at 22:41
  • `$event->job` does not refer to the actual job. This is a wrapper variant if you use a `sync` driver this will refer to a `syncJob` class if you use the `redis` driver it will refer to a `redisJob` etc. – Stephan-v Aug 12 '18 at 22:42
  • @alariva If my concrete job extends the abstract class it would normally be perfectly fine to perform an `instanceof` check. It seems I need to get the raw payload of the job though to get the original Job class. For all the ease of use in Laravel this feels really cumbersome to fetch the actual underlying Job. – Stephan-v Aug 12 '18 at 22:44

1 Answers1

0

I posted on your issue btw.

Could you try this and see if resolveName gives you the correct class name of your job/task:

Queue::before(function (JobProcessing $event) {
    $class = $event->job->resolveName();

    // without an instance
    if (is_a($class, AbstractTask::class, true)) {
        ...
    }

    // with an instance
    $instance = app($class);

    if ($instance instanceof AbstractTask) {
        ...
    }
});
lagbox
  • 48,571
  • 8
  • 72
  • 83