キュージョブ
GeneratePdfJob クラスは、PDF生成をバックグラウンドワーカーにオフロードするための既製のキュー可能なジョブを提供します。ビルダーコールバック、出力パスを受け取り、成功/失敗フック、リトライロジック、バッチディスパッチをサポートしています。
php
use Yeeefang\TcpdfNext\Laravel\Jobs\GeneratePdfJob;基本的なディスパッチ
新しい Document を受け取るコールバックと出力パスを渡します:
php
use Yeeefang\TcpdfNext\Core\Document;
GeneratePdfJob::dispatch(
callback: function (Document $pdf) {
$pdf->setTitle('Monthly Report')
->addPage()
->setFont('Helvetica', '', 12)
->cell(0, 10, 'Generated asynchronously');
},
outputPath: storage_path('reports/monthly.pdf'),
)->onQueue('pdf-generation');ジョブはコンテナから Document を解決し、コールバックに渡してから出力を書き込みます。
コンストラクタパラメータ
| パラメータ | 型 | 説明 |
|---|---|---|
callback | Closure(Document): void | PDFを構築するビルダー |
outputPath | string | 出力先パス(絶対パス、またはディスクルートからの相対パス) |
disk | ?string | Laravelファイルシステムディスク(デフォルト:ローカルファイル用に null) |
onSuccess | ?Closure(string): void | 成功時に出力パスとともに呼び出される |
onFailure | ?Closure(Throwable): void | 失敗時に例外とともに呼び出される |
成功と失敗のコールバック
php
GeneratePdfJob::dispatch(
callback: function (Document $pdf) {
$pdf->setTitle('Contract')
->addPage()
->setFont('Helvetica', 'B', 14)
->cell(0, 10, 'Service Agreement');
},
outputPath: 'contracts/SA-0042.pdf',
disk: 's3',
onSuccess: function (string $path) {
Notification::send($user, new ContractReady($path));
},
onFailure: function (Throwable $e) {
Log::error('Contract PDF failed', ['error' => $e->getMessage()]);
},
)->onQueue('pdf-generation');リトライロジック
標準のLaravelリトライ設定がサポートされています:
php
GeneratePdfJob::dispatch(
callback: fn (Document $pdf) => $pdf->addPage()->cell(0, 10, 'Retry demo'),
outputPath: storage_path('reports/demo.pdf'),
)
->onQueue('pdf-generation')
->tries(3)
->backoff([10, 30, 60]);デフォルトのリトライ値は config/tcpdf-next.php の queue キーで設定できます。
キュー接続の設定
PDFジョブを専用の接続にルーティングします:
php
GeneratePdfJob::dispatch(
callback: fn (Document $pdf) => $pdf->addPage()->cell(0, 10, 'Hello'),
outputPath: storage_path('output.pdf'),
)
->onConnection('redis')
->onQueue('pdf-generation')
->afterCommit();バッチPDF生成
Bus::batch() を使用して複数のPDFを並列で生成します:
php
use Illuminate\Support\Facades\Bus;
$jobs = $invoices->map(fn (Invoice $inv) =>
new GeneratePdfJob(
callback: function (Document $pdf) use ($inv) {
$pdf->setTitle("Invoice #{$inv->number}")
->addPage()
->setFont('Helvetica', 'B', 14)
->cell(0, 10, "Invoice #{$inv->number}");
},
outputPath: "invoices/{$inv->number}.pdf",
disk: 'local',
)
);
Bus::batch($jobs)
->name('Monthly Invoice Batch')
->onQueue('pdf-generation')
->allowFailures()
->then(fn () => Notification::send($admin, new BatchComplete()))
->catch(fn () => Log::warning('Some invoice PDFs failed'))
->dispatch();