Skip to content

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:

sh
tpf generate --pipeline pipeline.yaml --lang php --out ./generated

tpf generate writes a self-contained PHP namespace (Tpf\<PipelineName>) into --out containing:

  • types.php — declare(strict_types=1); final readonly class models for all canonical records and sealed union variants, TpfUnset presence 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 for ONE_TO_MANY, MANY_TO_ONE, and true interleaved full-duplex MANY_TO_MANY over 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 typePHP 8.2+ typePrecision guarantee
string, uuid, timestamp, date, durationstringExact UTF-8 / ISO-8601 string
boolboolNative bool
int32, int64intSigned 64-bit integer on 64-bit PHP (exact int64 > 2^53, including PHP_INT_MIN); 32-bit PHP fails closed at startup
decimalstringExact 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, float64floatIEEE-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 {})
unionSealed interface + tagged final readonly class variantsExplicit variant class per discriminator
Optional field omitted vs nullT|TpfUnset vs T|nullOmitted 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
<?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 Throwable instances are reported as UNCLASSIFIED (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
<?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:

sh
vendor/bin/phpunit

Then 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_MANY NDJSON frames incrementally.
  • Bind address: Keep the default TPF_BIND_HOST=127.0.0.1 when 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, set TPF_BIND_HOST to 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 CommandEffectStore and 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.

Diagram