PHP code example of dskripchenko / laravel-delayed-process
1. Go to this page and download the library: Download dskripchenko/laravel-delayed-process library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dskripchenko / laravel-delayed-process example snippets
declare(strict_types=1);
namespace App\Services;
final class ReportService
{
public function generate(int $userId, string $format): array
{
// Long-running operation (30+ seconds)
$data = $this->buildReport($userId, $format);
return ['url' => $data['url'], 'rows' => $data['count']];
}
}
use Dskripchenko\DelayedProcess\Contracts\ProcessProgressInterface;
final class ImportService
{
public function __construct(
private readonly ProcessProgressInterface $progress,
) {}
public function run(array $rows): array
{
foreach ($rows as $i => $row) {
$this->import($row);
$this->progress->setProgress(intdiv(($i + 1) * 100, count($rows)));
}
return ['imported' => count($rows)];
}
}
use Dskripchenko\DelayedProcess\Contracts\ProcessFactoryInterface;
final class ReportController extends ApiController
{
public function generate(
Request $request,
ProcessFactoryInterface $factory,
): JsonResponse {
$process = $factory->make(
ReportService::class,
'generate',
$request->integer('user_id'),
$request->string('format'),
);
return response()->json([
'success' => true,
'payload' => [
'delayed' => ['uuid' => $process->uuid, 'status' => $process->status->value],
],
]);
}
}
use Dskripchenko\DelayedProcess\Models\DelayedProcess;
use Dskripchenko\DelayedProcess\Resources\DelayedProcessResource;
Route::get('/api/common/delayed-process/status', function (Request $request) {
$process = DelayedProcess::query()
->where('uuid', $request->query('uuid'))
->firstOrFail();
return DelayedProcessResource::make($process);
});
use Dskripchenko\DelayedProcess\Contracts\ProcessFactoryInterface;
$process = $factory->make(
entity: \App\Services\ExportService::class,
method: 'exportCsv',
// Variadic parameters passed to the handler method:
$userId,
$filters,
);
// Stored as {"model": "App\\Models\\Article", "limit": 500}
$factory->make(ExportService::class, 'export', ...['model' => Article::class, 'limit' => 500]);
final class ExportService
{
public function export(string $model, Exporter $exporter, int $limit = 1000, string $format = 'csv'): array
{
// $exporter comes from the container, $format keeps its default
}
}
// config/delayed-process.php
'allowed_entities' => [
\App\Services\ReportService::class,
\App\Services\ExportService::class,
// Only these classes can be used as handlers
],