当您使用进度条并推进它时,您将在 ajax 中执行相同的操作,但进度逻辑将在偏离过程中有所不同。
这两种情况的共同点是处理每张卡的付款。所以我会说创建单独的类或服务,例如PaymentProcess
,处理卡支付实例并在成功或失败时返回。
然后在命令中你可以做(psuedocode):
公共函数句柄() { $pendingPayments = Payment::where('status', 'pending');
$bar = $this->output->createProgressBar($pendingPayments->count());
$pendingPayments->chunk(10, function($payments) use($bar){
$payments->each(function($payment) use ($bar){
$process = (new PaymentProcess($payment))->process();
$bar->advance();
});
});
$bar->finish();
}
现在,如果您从前端触发此操作,则 ajax 响应应该为您提供存储在某处的当前进程的 id。然后,您将以 1 秒的间隔继续发送另一个 ajx 请求并获取当前进度,直到达到 100%。(如果您使用的是 XMLHttpRequest2,那么逻辑会有所不同)
为此,您可以创建另一个表来存储进度,然后继续更新它。
现在同样你可以使用PaymentProcess
内部控制器。:
public function processPendingPayments(Request $request) { // 授权请求 $this->authorize('processPendingPayments', Payment::class);
$pendingPayments = Payment::where('status', 'pending');
// Create a progress entry
$progress = PaymentProgress::create([
'reference' => str_random('6')
'total' => $pendingPayments->count(),
'completed' => 0
]);
$pendingPayments->chunk(10, function($payments) use($bar){
$payments->each(function($payment) use ($bar){
$process = (new PaymentProcess($payment))->process();
// Update a progress entry
$progress->update([
'completed' => $progress->completed + 1;
]);
});
});
return response()->json([
'progress_reference' => $progress->reference
], 200);
}
现在另一个端点来获取进度
public function getProgress(Request $request) { // 授权请求 $this->authorize('getProgress', Payment::class);
$request->validate([
'reference' => 'required|exists:payment_process,reference'
]);
$progress = PaymentProcess::where('reference', $request->reference)->first();
$percentage = $progress->completed / $progress->total * 100;
return response()->json(compact('percentage'), 200);
}