Alpha ZealPHP is early-stage and under active development. APIs may change between minor versions until v1.0. Feedback and bug reports welcome on GitHub.
API Index — Namespaces, Packages, Reports, Indices

RequestIdMiddleware
in package
implements MiddlewareInterface

FinalYes

Request-ID middleware — assign every request a correlation id and echo it on the response, so a single request can be traced across logs, services, and the client. The kind of edge concern you'd add at Traefik/nginx, expressed as an in-process middleware that your handlers can also read.

Behaviour:

  • If the inbound request already carries the header (set by an upstream proxy), that value is trusted and propagated — unless $trustInbound is false, in which case a fresh id is always minted.
  • Otherwise a new id is generated (bin2hex(random_bytes(16)) → 32 hex chars, collision-safe).
  • The id is stored in the per-request memo so route handlers can read it (RequestContext::once('request_id', fn() => null) / RequestContext::has('request_id')), and written to the response header.

Stateless and coroutine-safe: the per-request id lives in $g (coroutine context), never on the middleware instance, so one shared instance serves every concurrent request.

Usage — global, per-route, or via an alias:

$app->addMiddleware(new RequestIdMiddleware());                  // every request
App::middlewareAlias('request-id', fn() => new RequestIdMiddleware());
$app->route('/api/job', middleware: ['request-id'], handler: $fn); // one route

Table of Contents

Interfaces

MiddlewareInterface

Properties

$headerName  : string
$trustInbound  : bool

Methods

__construct()  : mixed
process()  : ResponseInterface

Properties

Methods

__construct()

public __construct([string $headerName = 'X-Request-Id' ][, bool $trustInbound = true ]) : mixed
Parameters
$headerName : string = 'X-Request-Id'
$trustInbound : bool = true

process()

public process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
Parameters
$request : ServerRequestInterface
$handler : RequestHandlerInterface
Return values
ResponseInterface
On this page