laminas/laminas-diactoros
PSR-7 HTTP message implementation (ServerRequest, Request, Response, Stream, UploadedFile, Uri) for PHP. Includes factories and utilities for creating and normalizing requests/responses, with strong type coverage and interoperability with PSR-17/PSR-15.
Start by installing the package via Composer:
composer require laminas/laminas-diactoros
Begin with ServerRequestFactory::fromGlobals() to convert PHP superglobals into a PSR-7 ServerRequestInterface. This is the most common first step for middleware-based applications (e.g., in frameworks like Expressive/Laminas API Tools or customSlim/Expressive-style stacks). Immediately after, create a Response to build your output:
use Laminas\Diactoros\ServerRequestFactory;
use Laminas\Diactoros\Response;
$request = ServerRequestFactory::fromGlobals();
$response = new Response();
$response->getBody()->write('Hello world');
Use the README’s code samples for quick reference—especially the Server-Side Applications section.
ServerRequestFactory::fromGlobals() to standardize $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES → ServerRequestInterface. The factory intelligently parses cookies from headers when no explicit $cookies array is provided.with*() methods:
$request = $request->withAddedHeader('X-Request-ID', uniqid());
$response = $response->withStatus(201);
$response->getBody() for writing content. Supports resource streams (fopen()), php://memory, and custom StreamInterface implementations.Request\Serializer and Response\Serializer for debugging or logging (e.g., in middleware or CLI jobs):
$logData = [
'request' => Request\Serializer::toString($request),
'response' => Response\Serializer::toString($response),
];
ArraySerializer::toArray() for structured logging—especially useful in structured JSON logs or telemetry tools (e.g., Sentry, Datadog).laminas/laminas-httphandlerrunner for production-ready request handling (replacing the now-deprecated Server class).Server class: Do not use Laminas\Diactoros\Server for new work—it was deprecated in v1.8. Prefer laminas/laminas-httphandlerrunner (RequestHandlerRunner).with*() methods. Always assign:
// ❌ Wrong: $request unchanged
$request->withHeader(...);
// ✅ Correct
$request = $request->withHeader(...);
foo.bar → foo_bar). Use fromGlobals() without $cookies to pull cookies from the raw Cookie header instead.StreamInterface is a resource handle—don’t try to write to it after it’s been consumed (e.g., after calling getContents() once). Clone if needed:
$clonedBody = $request->getBody()->detach() ? $request->getBody()->__clone() : $request->getBody();
fromGlobals(); instead, manually construct ServerRequest or Request instances with new + with*() methods for full control over test context.ServerRequest/Response between middleware layers, remember immutability means each handler receives the original object unless you return a modified response.How can I help you explore Laravel packages today?