Symfony — Bundle 整合套件¶
NextPDF Symfony
nextpdf/symfony 以標準 Symfony Bundle 形式整合 NextPDF Core,遵循 Symfony 的依賴注入、服務容器與 Messenger 慣例。Bundle 提供自動服務接線(autowiring)、完整的 YAML/XML/PHP 設定支援,以及透過 Symfony Messenger 實現非同步 PDF 生成。
PHP Compatibility
This example uses PHP 8.5 syntax. If your environment runs PHP 8.1 or 7.4, use NextPDF Backport for a backward-compatible build.
核心元件¶
| 元件 | 功能 |
|---|---|
NextPdfBundle | Bundle 主類別,負責 Extension 與 CompilerPass 注冊 |
NextPdfExtension | DI Extension,解析 Bundle 設定並注冊服務 |
PdfFactory | 封裝 DocumentFactoryInterface,提供 Symfony 風格的工廠服務 |
GeneratePdfMessage | Messenger 訊息 DTO |
GeneratePdfHandler | Messenger 訊息處理器 |
安裝¶
在 config/bundles.php 中啟用 Bundle:
Symfony Flex 會自動執行此步驟(若安裝了 symfony/flex)。
快速開始¶
<?php
declare(strict_types=1);
namespace App\Controller;
use NextPDF\Symfony\Service\PdfFactory;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
final class ReportController
{
public function __construct(
private readonly PdfFactory $pdfFactory,
) {}
#[Route('/reports/{id}/download', name: 'report_download')]
public function download(int $id): Response
{
$document = $this->pdfFactory->create(title: "Report #{$id}");
$document->addPage();
$document->text("Report content", x: 20, y: 30);
return new Response(
content: $document->output(),
headers: [
'Content-Type' => 'application/pdf',
'Content-Disposition' => "attachment; filename=\"report-{$id}.pdf\"",
],
);
}
}
依賴注入(Autowiring)¶
Bundle 將以下服務暴露為可 autowire 的容器服務:
| 服務 ID | 型別提示 | 說明 |
|---|---|---|
nextpdf.process | NextPDF\Core\Contracts\ProcessInterface | 共享 Process 實例 |
nextpdf.factory | NextPDF\Core\Contracts\DocumentFactoryInterface | 文件工廠 |
nextpdf.pdf_factory | NextPDF\Symfony\Service\PdfFactory | Symfony 封裝工廠 |
// 透過建構子注入(建議方式)
public function __construct(
private readonly PdfFactory $pdfFactory, // autowire 別名
private readonly DocumentFactoryInterface $docFactory, // Core 介面
) {}
非同步 Messenger 整合¶
use NextPDF\Symfony\Messenger\GeneratePdfMessage;
// 派送訊息(非同步)
$this->messageBus->dispatch(
new GeneratePdfMessage(
templateKey: 'invoice',
parameters: ['invoiceId' => 42],
notifyEmail: '[email protected]',
),
);
參見¶
- Bundle 設定 — YAML/XML 設定完整參考
- Messenger — GeneratePdfMessage/Handler 詳細說明
- PdfFactory — 工廠服務 API 參考