有什么方法可以在laravel 5中调度关闭? [英] Any way to dispatch a closure in laravel 5?

查看:37
本文介绍了有什么方法可以在laravel 5中调度关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在laravel 4中,我可以使用 queue :: push(function ...)将闭包推送到队列中,但这在laravel 5中不再起作用.为要推送到队列中的每个函数创建一个自定义Job类.

In laravel 4, I could push a closure onto the queue with queue::push(function...), but this no longer works in laravel 5. Instead, it appears that I have to make a custom Job class for every function that I want to push onto the queue.

由于我要推送的功能只有几行,并且只能在一个地方使用,因此为每种情况编写一个完整的类真的很浪费时间和空间.

Since the functions I want to be pushing are only a couple of lines long, and are only ever used in exactly one place, it really seems like a waste of time and space to be writing up a full class for every case.

我目前能想到的最好的解决方案"是拥有一个使用PHP的反射方法的助手函数,该函数在调用时动态生成一个新类,或者让一个通用工作接受一个闭包作为参数,即 dispatch(new ClosureJob(function(){...}));

The best "solutions" I can currently think of, are to either have a helper function that uses PHP's reflection methods to dynamically generate a new class when called, or to have generic job that accepts a closure as parameter, i.e. dispatch(new ClosureJob(function(){...}));

这些对我来说似乎并不理想.还有另一种方法吗?还是我必须实施其中之一?

These seem less than ideal to me. Is there another way to do this? Or am I going to have to implement one of these?

推荐答案

我已经通过依赖 OpisClosure 库.像这样扩展类:

I've accomplished this by relying on the OpisClosure library. Extend the class as so:

class QueueableClosure extends SerializableClosure
{
    public function handle() {
        call_user_func_array($this->closure, func_get_args());
    }
}

然后像这样使用它:

Queue::push(new QueueableClosure(function(){
    Log::debug("this is the QueueableClosure in action.");
}));

N.B.请参阅以下来自@Quezler的评论,以了解可能的限制!

N.B. See the comment below from @Quezler about possible limitations!

这篇关于有什么方法可以在laravel 5中调度关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆