在laravel 4中,我可以使用queue::push(function...)
将一个闭包推到队列中,但这不再适用于laravel 5.相反,我似乎必须为我想要推送到队列的每个函数创建一个自定义Job类。
由于我想要推动的功能只有几行,并且只在一个地方使用过,所以为每种情况写一个完整的类似乎浪费时间和空间。
我目前可以想到的最好的“解决方案”是要么有一个辅助函数,它使用PHP的反射方法在调用时动态生成一个新类,或者具有接受闭包作为参数的通用作业,即dispatch(new ClosureJob(function(){...}));
这对我来说似乎不太理想。还有另一种方法吗?或者我将不得不实施其中之一?
我依靠OpisClosure库完成了这项工作。像这样扩展类:
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.");
}));
注:请参阅@Quezler下面的评论,了解可能的限制!
https://laravel.com/docs/5.0/queues#queueing-closures说:
您也可以将Closure推入队列。这对于需要排队的快速,简单的任务非常方便:
将关闭推到队列上
Queue::push(function($job) use ($id)
{
Account::delete($id);
$job->delete();
});
但是,我的猜测是你使用的是Laravel 5.3+,因为https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0说:
不再支持排队闭包。如果要在应用程序中对Closure进行排队,则应将Closure转换为类并对该类的实例进行排队。