跳到內容

NextPDF 與 Cloudflare 整合

本頁完整涵蓋端到端流程:安裝套件、完成設定、算繪一份 PDF,並視需要封存結果。整個流程都透過 Cloudflare Worker 與 R2 驅動 NextPDF 算繪。這是一份操作指南,請搭配概念說明 /integrations/cloudflare/overview/ 與參考文件 /integrations/cloudflare/configuration/ 使用。

Terminal window
composer require nextpdf/cloudflare:^0.1

接著,加入一個 PSR-18 用戶端與多個 PSR-17 工廠,例如 Guzzle 7。本套件只宣告 PSR 契約,本身不隨附任何具體用戶端,因此需要由你自行提供。完整細節請參閱 /integrations/cloudflare/install/。

這個橋接器沒有 service provider,也沒有 bundle,而是直接由 PSR 協作物件與一個 CloudflareRendererConfig 建構。宿主框架會重用應用程式既有的 PSR-18 繫結,再將橋接器繫結到自身的容器中。完整啟動序列與容器繫結範例,請參閱 /integrations/cloudflare/boot-and-discovery/。

CloudflareHtmlRenderer 繫結為單例(singleton)。提供 PSR-18 用戶端、PSR-17 請求與串流工廠,以及一個選用的 PSR-3 記錄器。若要使用釘選的 cURL 傳輸層,還需額外提供一個 PSR-17 回應工廠。繫結範例請見 /integrations/cloudflare/boot-and-discovery/。

本套件會從 CloudflareRendererConfig 讀取設定。機密資訊應取自環境變數,絕不可取自已提交的檔案:

<?php
declare(strict_types=1);
use NextPDF\Cloudflare\CloudflareRendererConfig;
$config = CloudflareRendererConfig::fromArray([
'worker_url' => getenv('CF_WORKER_URL') ?: '',
'api_token' => getenv('CF_PDF_TOKEN') ?: '',
'render_timeout' => 60,
'r2_font_bucket' => getenv('CF_R2_FONT_BUCKET') ?: null,
]);

workerUrl 必須是 HTTPS。apiToken 標註為 #[SensitiveParameter]。完整欄位參考請參閱 /integrations/cloudflare/configuration/,其中涵蓋 SPKI 釘選欄位以及所有預設值。R2 封存設定與 API 保護層則涵蓋於 /integrations/cloudflare/production-usage/。

沒有 service provider 可供冒煙測試;對應的啟動檢查如下:

$config = CloudflareRendererConfig::fromArray($appConfig['cloudflare']);
assert($config->isValid(), 'Cloudflare config incomplete');
// Optional runtime reachability check (authenticated HTTP HEAD):
if (!$renderer->isAvailable()) {
// Worker not reachable — degrade or alert.
}

isValid() 只做完整性檢查,不會發出任何網路呼叫。isAvailable() 會執行一次帶驗證的 HEAD 請求。當 Worker 無法運作時,它會回傳 false,而不會擲出例外。

本套件的公開介面全都位於 NextPDF\Cloudflare\ 之下:

型別角色
CloudflareHtmlRenderer算繪進入點:render()isAvailable()getHtmlSecurityPolicy()
CloudflareRendererConfig算繪器設定(fromArray()isValid()allPublicKeyPins())。
CloudflareRenderResult具型別算繪結果(isValid()size())。
CloudflareRenderPayloadWorker JSON 酬載(toJson())。
CloudflareResponseParserWorker 回應 → 結果剖析器。
CloudflareSecurityPolicy輸入與 URL 驗證。
Transport\PinnedCurlTransport採用 DNS 釘選/TLS 釘選的 PSR-18 傳輸層。
Contract\LocalRendererFactoryInterfaceContract\LocalRendererInterface本地後備(fallback)契約。
ApiProtectionApiProtectionConfigApiProtectionResultApiKeyValidator入站 API 保護。
R2ArchiveManagerR2ArchiveConfigR2ObjectKeyR2UploadResultR2 封存。
Exception\CloudflareRenderExceptionException\CloudflareNotAvailableExceptionException\InvalidSpkiPinException例外階層。

完整算繪流程的逐步教學,請參閱 /integrations/cloudflare/quickstart/。正式環境的接線方式位於 /integrations/cloudflare/production-usage/,其中涵蓋後備機制、遙測、封存與保護。

  • /integrations/cloudflare/overview/ —— 信任邊界與邊緣算繪模型。
  • /integrations/cloudflare/quickstart/ —— 可實際執行的首次算繪。
  • /integrations/cloudflare/boot-and-discovery/ —— 容器接線細節。
  • /integrations/cloudflare/security-and-operations/ —— SSRF 防禦、釘選,以及維運手冊。
  • /integrations/cloudflare/troubleshooting/ —— 對應各例外的失敗模式。