【发布时间】:2019-07-07 12:47:03
【问题描述】:
我正在使用 Laravel 4.2 队列功能。现在我有一个函数将对数据进行处理,然后将一些结果返回给函数。我的问题是,如何检查从队列返回的状态?
代码
控制器功能
public function destroy($id, $message = '')
{
//Calling queue
Queue::push('InvoiceQueue@delete_invoice', [
'id' => $id,
'Class' => $this->Class,
]);
//continue the function after returned from the queue
//Do validation based on queue returned status
$instance = $this->Class;
$record = $instance::findOrFail($id);
//Restore the DB if queue returned an error
if ($record->restore()) {
}
//Delete the DB if queue process working fine
else {
return parent::destroy($id, trans("$this->class.invoice"));
}
}
队列功能
public function delete_invoice($job, $data)
{
try {
return DB::transaction(function ()use ($job,$data) {
//Doing some process here, go to Catch if an error
});
} catch (TransactionException $e) {
return Response::json(['errors' => array_flatten($e->getErrors())], 400);
}
}
我不确定如何根据队列返回的结果在控制器函数中进行验证。上面的代码总是执行restore(),从不去else语句。
【问题讨论】:
-
委托队列的全部意义在于在当前上下文之外执行该代码,因此您的代码不必等待队列作业完成。这意味着该作业无法返回任何结果。如果您依赖特定代码段的结果来继续您的控制器操作,那么您应该直接调用该方法/函数而不将其推送到队列中。