Laravel check if job extends a certain class

99封情书 提交于 2019-12-10 11:54:29

问题


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


回答1:


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) {
        ...
    }
});


来源:https://stackoverflow.com/questions/51813393/laravel-check-if-job-extends-a-certain-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!