PHP ​
Write TPF business steps and Tier-2 custom Connector adapters in PHP 8.2+ (64-bit) using only the PHP standard library — no Composer packages, no optional extensions (bcmath and pcntl are optional), and no JVM required for local development. The native tpf CLI generates final readonly value classes and a non-blocking Fiber HTTP/1.1 host directly from your canonical v3 pipeline.yaml.
1. Generate PHP types and host bindings ​
Run tpf generate against your pipeline.yaml:
tpf generate --pipeline pipeline.yaml --lang php --out ./generatedtpf generate writes a self-contained PHP namespace (Tpf\<PipelineName>) into --out containing:
types.php—declare(strict_types=1);final readonly classmodels for all canonical records and sealed union variants,TpfUnsetpresence sentinel,FunctionContext,QueryConnectorContext,CommandConnectorContext,CommandReconcileContext,FunctionHandlers,ConnectorHandlers(when custom Connectors are declared), and portable exception classes (TpfBusinessRejectionException,TpfTransientException).host.php—Host::start(...)and$host->serve()implementing a strict RFC-8259 exact numeric JSON codec (TpfJson::parseExact/encodeCanonical), HMAC-SHA256 verification with timezone-aware ISO-8601 timestamp skew validation and bounded nonce replay protection, NDJSON streaming forONE_TO_MANY,MANY_TO_ONE, and true interleaved full-duplexMANY_TO_MANYover non-blocking sockets and PHP 8.2+Fibers, plus loopback Connector listener challenge authentication.META-INF/pipeline/pipeline-contract.json— the compiled canonical v3 contract (byte-identical to TypeScript and Python builds).
2. Canonical type mapping in PHP ​
| Canonical v3 type | PHP 8.2+ type | Precision guarantee |
|---|---|---|
string, uuid, timestamp, date, duration | string | Exact UTF-8 / ISO-8601 string |
bool | bool | Native bool |
int32, int64 | int | Signed 64-bit integer on 64-bit PHP (exact int64 > 2^53, including PHP_INT_MIN); 32-bit PHP fails closed at startup |
decimal | string | Exact base-10 decimal string parsed directly from the raw JSON token and serialised back as an unquoted JSON number without IEEE-754 float conversion (interoperable with bcmath, PHP 8.4 BcMath\Number, or brick/math) |
float32, float64 | float | IEEE-754 floating point |
list<T> | array (list<T>) | Ordered list |
map<string, V> | array (array<string, V>) | String-keyed associative array (empty maps always serialise as {}) |
union | Sealed interface + tagged final readonly class variants | Explicit variant class per discriminator |
Optional field omitted vs null | T|TpfUnset vs T|null | Omitted fields default to new TpfUnset() and are not serialised as null |
3. Implement business functions ​
Implement the generated FunctionHandlers interface. Streaming steps accept and yield standard PHP iterable / \Generator values so full-duplex MANY_TO_MANY steps emit outputs incrementally as inputs arrive on the same HTTP/1.1 connection.
<?php
declare(strict_types=1);
require_once __DIR__ . '/generated/host.php';
use Tpf\InvoicePipeline\FunctionContext;
use Tpf\InvoicePipeline\FunctionHandlers;
use Tpf\InvoicePipeline\Host;
use Tpf\InvoicePipeline\Invoice;
use Tpf\InvoicePipeline\InvoiceSummary;
use Tpf\InvoicePipeline\LineItem;
use Tpf\InvoicePipeline\TpfBusinessRejectionException;
use Tpf\InvoicePipeline\TpfTransientException;
final class Handlers implements FunctionHandlers
{
// ONE_TO_ONE
public function validateInvoice(Invoice $input, FunctionContext $ctx): Invoice
{
if (str_starts_with($input->amount, '-')) {
throw new TpfBusinessRejectionException('NEGATIVE_AMOUNT', 'Invoice amount must be positive');
}
return new Invoice(
invoiceId: $input->invoiceId,
sequenceNumber: $input->sequenceNumber + 1,
amount: $input->amount,
);
}
// ONE_TO_MANY
public function expandLines(Invoice $input, FunctionContext $ctx): iterable
{
yield new LineItem(sku: $input->invoiceId . '-A', lineTotal: $input->amount);
}
// MANY_TO_MANY (full-duplex incremental generator)
public function enrichLines(iterable $inputs, FunctionContext $ctx): iterable
{
foreach ($inputs as $line) {
yield new LineItem(
sku: strtoupper($line->sku),
lineTotal: $line->lineTotal,
);
}
}
// MANY_TO_ONE
public function summariseInvoice(iterable $inputs, FunctionContext $ctx): InvoiceSummary
{
$total = '0';
$scale = 0;
$count = 0;
foreach ($inputs as $line) {
// Preserve the full decimal scale of every input (or use PHP 8.4 BcMath\Number / brick/math)
$dot = strpos($line->lineTotal, '.');
if ($dot !== false) {
$scale = max($scale, strlen($line->lineTotal) - $dot - 1);
}
$total = bcadd($total, $line->lineTotal, $scale);
$count++;
}
if ($count === 0) {
throw new TpfTransientException('EMPTY_BATCH', 'Upstream produced no line items');
}
return new InvoiceSummary(invoiceId: "batch-{$count}", grandTotal: $total);
}
}
$host = Host::start(
handlers: new Handlers(),
sharedSecret: getenv('TPF_SHARED_SECRET') ?: '',
host: getenv('TPF_BIND_HOST') ?: '127.0.0.1',
port: (int) (getenv('PORT') ?: '0'),
);
fwrite(STDOUT, 'READY ' . $host->baseUrl() . "\n");
fflush(STDOUT);
$host->serve();Portable failure classification ​
- Throw
TpfBusinessRejectionException($code, $message)for deterministic domain rejections (BUSINESS_REJECTION, non-retryable). - Throw
TpfTransientException($code, $message)for retryable transient errors (TRANSIENT). - Unhandled PHP
Throwableinstances are reported asUNCLASSIFIED(non-retryable by default) while keeping the Fiber host process healthy.
4. Author a Tier-2 custom Connector (optional) ​
For external providers that require a PHP SDK, implement the generated ConnectorHandlers interface and pass it as the second argument to Host::start(handlers: new Handlers(), connectors: new Connectors(), ...):
<?php
declare(strict_types=1);
use Tpf\InvoicePipeline\CommandConnectorContext;
use Tpf\InvoicePipeline\CommandReconcileContext;
use Tpf\InvoicePipeline\ConnectorHandlers;
use Tpf\InvoicePipeline\LedgerReceipt;
use Tpf\InvoicePipeline\LedgerRequest;
use Tpf\InvoicePipeline\QueryConnectorContext;
use Tpf\InvoicePipeline\RateQuote;
use Tpf\InvoicePipeline\RateRequest;
final class Connectors implements ConnectorHandlers
{
public function queryLookupRate(RateRequest $input, QueryConnectorContext $ctx): array
{
$apiKey = $ctx->secrets['FX_API_KEY'];
// Call external PHP SDK using $apiKey...
return [
'outcome' => 'FOUND',
'payload' => new RateQuote(currency: $input->currency, rate: '1.08450000'),
];
}
public function dispatchSubmitLedger(LedgerRequest $input, CommandConnectorContext $ctx): array
{
// Use $ctx->dispatchIdentity->providerIdempotencyKey for idempotent submission
return [
'outcome' => 'SUCCEEDED',
'payload' => new LedgerReceipt(entryId: 'led-100'),
'providerReference' => 'ext-ref-100',
];
}
public function reconcileSubmitLedger(CommandReconcileContext $ctx): array
{
return [
'outcome' => 'CONFIRMED_SUCCEEDED',
'payload' => new LedgerReceipt(entryId: 'led-100'),
'providerReference' => 'ext-ref-100',
];
}
}The Java execution engine persists the CommandEffectStore and QueryCaptureStore records, enforces RETURN_RECORDED replay, and invokes reconcile<Operation> when an outcome is AMBIGUOUS.
5. Run, test, and deploy cleanly ​
Unit-test handlers without a JVM ​
Unit-test your FunctionHandlers methods directly with PHPUnit by passing plain final readonly inputs:
vendor/bin/phpunitThen run the full pipeline end-to-end with tpf dev (see Local Development and Testing without a JVM).
Production hosting note: long-lived Fiber host vs PHP-FPM ​
Run the generated PHP host (php app.php) as a long-lived process or container behind a co-located internal TLS reverse proxy (such as an Nginx sidecar on loopback with proxy_http_version 1.1, proxy_buffering off, proxy_request_buffering off, and a workload-appropriate client_max_body_size or 0 for streaming, or Envoy/Caddy/a service mesh configured for unbuffered bidirectional streaming) rather than behind PHP-FPM:
- Why: PHP-FPM buffers full request and response bodies per worker invocation and cannot stream interleaved full-duplex
MANY_TO_MANYNDJSON frames incrementally. - Bind address: Keep the default
TPF_BIND_HOST=127.0.0.1when the TLS reverse proxy runs as a co-located sidecar in the same pod or host. If the proxy runs in another container or host, setTPF_BIND_HOSTto an internal interface reachable by the proxy and protect the proxy-to-host hop with TLS/mTLS (never forward signed requests over plaintext HTTP across a network). - How to scale & nonce replay scope: You can run multiple replicas of the PHP host behind your internal TLS terminator, keeping pure business function hosts separate from Tier-2 custom Connector hosts with distinct HMAC secrets. Note that the generated host's bounded nonce replay cache lives in process memory per replica — there is no built-in shared cross-replica HTTP nonce store. Cross-replica replay within the timestamp skew window is mitigated on the transport layer only when TLS/mTLS protects the entire path from the engine to the PHP host (either via a co-located loopback sidecar or TLS/mTLS on the proxy-to-host hop as well, preventing request capture in transit) and, for Tier-2 Command Connectors, by the engine-owned
CommandEffectStoreand idempotent provider submission via$ctx->dispatchIdentity->providerIdempotencyKey. If your threat model requires strict cross-replica HTTP nonce deduplication for non-idempotent Tier-2 Connector endpoints, enforce it at an upstream API gateway/shared store or restrict that Connector host to a single active replica. See Deploying Polyglot Applications.