05 / HTTP messages
Separate message immutability from stream state.
Request and Response use immutable with* message operations. Body streams are mutable and shared when messages are cloned; use withBody() with a separate stream to isolate content. Uri has immutable component operations.
REQUEST
Request
Request implements ServerRequestInterface with immutable attributes, cookies, query parameters, uploaded-file trees, and parsed body state. Matched route parameters and middleware context use the same request attributes.
<?php
declare(strict_types=1);
use dvictorjhg\braidphp\Router\Http\HttpMethod;
use dvictorjhg\braidphp\Router\Http\Request;
require_once __DIR__ . '/vendor/autoload.php';
$request = new Request(
method: HttpMethod::GET,
uri: 'http://example.test:8080/hello?name=Ada',
body: '',
);
$routed = $request
->withAttribute('scope', 'demo')
->withHeader('X-Trace', 'one')
->withAddedHeader('X-Trace', 'two');
echo ($request->getAttribute('scope') ?? 'none') . "\n";
echo $routed->getHeaderLine('x-trace') . "\n";
echo $routed->getHeaderLine('host') . "\n";
Expected outputnone
one,two
example.test:8080
RESPONSE
Response
Response implements ResponseInterface and supplies known reason phrases. ResponseEmitter owns native HTTP output and adds Content-Type and Content-Length when absent.
<?php
declare(strict_types=1);
use dvictorjhg\braidphp\Router\Http\Response;
use dvictorjhg\braidphp\Router\Http\ResponseEmitter;
require_once __DIR__ . '/vendor/autoload.php';
$response = new Response(
statusCode: 201,
body: 'welcome',
);
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
$output = fopen('php://output', 'w');
ResponseEmitter::write($output, $response);
fclose($output);
Expected output201
Created
HTTP/1.1 201 Created
Content-Type: text/plain
Content-Length: 7
welcome
PSR-15 middleware
Register MiddlewareInterface instances with App::addMiddleware(). They run before routing in registration order and unwind in reverse order. A middleware can short-circuit or condition its work on the request path. Route parameters are added to the controller's request copy, not the middleware's original request. App implements RequestHandlerInterface; handle() accepts ServerRequestInterface and returns ResponseInterface. listen() uses the same pipeline.
PSR-15 middlewarePHP
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use dvictorjhg\braidphp\Core\App;
use dvictorjhg\braidphp\Router\Http\Request;
use dvictorjhg\braidphp\Router\Router;
$app = new App([Router::class]);
$app->addMiddleware(new class implements MiddlewareInterface {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return $handler->handle($request)->withHeader('X-Frame-Options', 'DENY');
}
});
$response = $app->handle(new Request(uri: '/missing', body: ''));
echo $response->getStatusCode() . ' ' . $response->getHeaderLine('X-Frame-Options');
Register exception-to-response middleware first to wrap the entire pipeline. Direct calls propagate uncaught exceptions; listen() logs application errors and attempts a generic 500. Reused middleware stores request state in attributes. Controllers read path parameters with getAttribute(). Controller responses enter middleware unchanged; middleware may modify or replace them. ResponseEmitter accepts the resulting ResponseInterface without replacing its implementation.
Native Request construction defaults to PHP server/cookie globals and form POST data. Explicit serverParams disables global server, cookie, header, and form inference, but a null body still opens php://input; pass body: '' to avoid that. HttpFactory supplies explicit bodies and server parameters without importing globals. Native TCP input is not decoded into cookie parameters, JSON data, form fields, or uploaded files. Supply parsing middleware with withCookieParams(), withParsedBody(), and withUploadedFiles(). Request does not normalize $_FILES automatically, including under a SAPI. MiddlewarePipeline also supports a custom terminal RequestHandlerInterface.
PSR-17 factories and PSR-3 logging
HttpFactory implements all six factory interfaces: request, response, server request, stream, uploaded file, and URI. Requests do not import PHP globals. Valid extension-method tokens are accepted as message values; routing still uses HttpMethod. App accepts any LoggerInterface through its logger constructor argument.
PSR-17 factories and PSR-3 loggingPHP
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use dvictorjhg\braidphp\Core\App;
use dvictorjhg\braidphp\Core\ErrorLogLogger;
use dvictorjhg\braidphp\Router\Http\HttpFactory;
use dvictorjhg\braidphp\Router\Router;
$factory = new HttpFactory();
$app = new App([Router::class], logger: new ErrorLogLogger());
$request = $factory->createServerRequest('GET', '/missing', ['REMOTE_ADDR' => '127.0.0.1']);
$response = $factory->createResponse(201)
->withHeader('Content-Type', 'text/plain')
->withBody($factory->createStream('created'));
echo $response->getStatusCode() . ' ' . $response->getBody() . PHP_EOL;
echo $app->handle($request)->getStatusCode();
Expected output201 created
404
createStreamFromFile() opens a file and createStreamFromResource() requires a readable stream resource. createUploadedFile() validates size and upload-error metadata. UploadedFile::moveTo() accepts local paths, checks writes, and prevents repeat moves or stream access after success. Client filenames and media types remain untrusted metadata; multipart parsing is not bundled.
Listener failures are logged at error level with context['exception']. Malformed requests and uncaught application errors produce generic 400/500 responses when writing succeeds. Response-write failures are logged and the connection closes without a replacement response. ErrorLogLogger accepts all eight standard levels and logs message text plus throwable details without placeholder interpolation. If a custom logger throws, the listener falls back to error_log(). Direct handle() calls still propagate uncaught exceptions.
Message construction and mutation validate numeric protocol versions, 100-599 response status codes, and valid reason phrases. URIs preserve percent-encoded delimiters; route parameters are decoded once and keep literal plus signs. Ports must be 0-65535 or null; standard HTTP/HTTPS ports are omitted. Stream capabilities follow native modes, including append and exclusive-create variants.
Implemented PHP-FIG standards
Use PSR-7 interfaces for messages, PSR-15 for middleware and handlers, PSR-17 for factories, and PSR-3 for listener logging. Accept interfaces in application services to avoid coupling them to a specific implementation.
Register application-selected cache, event, clock, HTTP client, or link services as providers when needed; these services are not bundled. The router's internal path-segment cache is not a general PSR-6/PSR-16 cache API.
| Standard | Implemented support |
| PSR-7 | Messages, server requests, responses, URIs, streams, and uploaded files. |
| PSR-11 | PHPInjector provides the container. App accepts its concrete Container, not arbitrary ContainerInterface implementations. |
| PSR-15 | App is a RequestHandlerInterface with ordered MiddlewareInterface registration. |
| PSR-17 | HttpFactory implements all six HTTP factory interfaces from psr/http-factory. |
| PSR-3 | App accepts LoggerInterface; ErrorLogLogger is the default, with fallback logging for a failing custom backend. |
PHP-FIG standards index
| Component |
Actual behavior |
Notes |
Request |
Implements ServerRequestInterface, including RequestInterface. |
Query parameters come from the URI; matched route parameters are immutable attributes. |
Response |
Owns response status, headers, and a stream body. ResponseEmitter writes any ResponseInterface to a native stream with checked writes and deadlines. |
Explicit Content-Length and Content-Type headers are preserved. |
Uri |
Implements UriInterface with immutable components and percent-encoding normalization. |
The router splits getPath() from any PSR URI implementation. |
Stream |
Implements StreamInterface over native PHP stream resources. |
Detached streams reject tell/read/write/seek/eof/getContents operations. |
HttpFactory |
Implements all six PSR-17 factory interfaces. |
Factory requests are isolated from PHP globals. Use StreamFactory::create() to convert a value into a body stream. |
Action result conversion
- Actions may return any
ResponseInterface; middleware may modify the response. null, scalars, native PHP stream resources, PSR streams, and stringable objects are wrapped into new Response(200, [], ...).- Arrays are rejected explicitly by
App::responseFromResult(). - Objects that are neither stringable nor streams fail when the body is converted into a stream.
Serialization and streams
- Header names are case-insensitive and preserve the original output casing used when they were set.
withHeader(), withAddedHeader(), withoutHeader(), withBody(), and URI with* methods are immutable.StreamFactory::create() accepts scalar values, native stream resources, stringable objects, existing PSR streams, or null.- For seekable streams, serialization preserves content plus readable/writable/seekable flags. A non-seekable stream can serialize with empty content because rewinding fails.