PSR-7 / PSR-15 / PSR-17 / PSR-3

BraidPHP

BraidPHP combines attribute routes, modules, dependency injection, and PSR HTTP APIs. Use App::handle() for request handling or App::listen() for the bundled blocking TCP listener.

09HTTP method attributes
PSRmessages, middleware, factories
1Pblocking process model
Example/Controllers/GreeterComponent.php
<?php

namespace dvictorjhg\braidphp\Example\Controllers;

use dvictorjhg\braidphp\Router\Attributes\Get;
use dvictorjhg\braidphp\Router\Attributes\Route;
use dvictorjhg\braidphp\Router\Http\Request;
use dvictorjhg\braidphp\Example\Providers\GreeterProvider;

#[Route(path: '/api')]
final class GreeterComponent
{
    public function __construct(private GreeterProvider $greeterProvider)
    {
    }

    #[Get('/hello/:name')]
    public function greet(Request $request): string
    {
        $name = $request->getAttribute('name') ?? '';
        return $this->greeterProvider->getGreeting($name);
    }
}
Try it
curl http://127.0.0.1:8000/api/hello/Ada
# Hello Ada!
01 / Overview

Know what the framework does before you write code.

Start with a working application, then learn how to compose modules, declare routes, and handle HTTP messages. The later sections cover middleware, application testing, server configuration, and deployment boundaries.

What BraidPHP is

Attribute-driven routing plus a small runtime.

BraidPHP combines module composition, attribute routes, PSR-7 messages, PSR-15 middleware, PSR-17 factories, and PSR-3 listener logging. Dependency injection and provider storage come from dvictorjhg/php-injector.

Runtime model

Native listener: one request at a time.

App::listen() accepts, parses, handles, writes, and closes each client connection sequentially. It does not create workers or run an event loop. App::handle() processes an existing PSR-7 server request without opening a socket; adapting it to another server is application work.

Area Key components What to expect
Modules App, #[Module] Application bootstrap, module ordering, imports, providers, controllers, and bootstrap services.
Routing Router, #[Route], #[Get], HttpMethod Route matching, path parameters, custom matchers, request parsing, response serialization, URI and stream helpers.
HTTP Request, Response, HttpFactory, MiddlewareInterface Create messages, wrap request handling in middleware, and integrate PSR-compatible libraries through shared interfaces.
Runtime App::handle(), App::listen(), HttpOptions Handle an existing server request or run the native TCP listener with configurable byte limits and read/write deadlines.
Prerequisites
  • PHP 8.4.27 or later in the 8.4 series, or PHP 8.5.12 and later PHP 8.x releases. PHP 8.5.0-8.5.11 and PHP 9 are outside the package constraint.
  • Composer
  • A second terminal for curl while the server keeps running
Integration boundaries
  • Middleware is registered on App, not on route declarations. It can inspect the request path to restrict its behavior.
  • The native listener has no worker manager or event loop. Multiple listener processes need external supervision and traffic distribution.
  • The TCP listener leaves multipart input as a raw body. Supply parsing middleware to populate parsed fields and uploaded files.
  • No template engine, ORM, or session layer is bundled. Register application-selected services through providers; compatibility depends on the library and runtime.
02 / First application

Build the smallest working app from an empty directory.

This walkthrough creates only the files the framework needs: composer.json, a PSR-4 src/ tree, one module, one controller, one provider, and a front controller that starts App::listen().

01

Create the project and install BraidPHP.

Start with a composer.json that requires security-patched PHP, requires the package, and maps the App namespace to src/.

{
    "name": "acme/hello-braid",
    "require": {
        "php": "~8.4.27 || ^8.5.12",
        "dvictorjhg/braidphp": "^1.2"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}
Runcomposer install
02

Add one provider and one controller.

The provider is a plain PHP class. The controller uses a class prefix and a GET route that reads the captured :name parameter from the immutable request copy.

src/Greeter.php

<?php

declare(strict_types=1);

namespace App;

final class Greeter
{
    public function greeting(string $name): string
    {
        return "Hello $name!";
    }
}

src/GreetingController.php

<?php

declare(strict_types=1);

namespace App;

use dvictorjhg\braidphp\Router\Attributes\Get;
use dvictorjhg\braidphp\Router\Attributes\Route;
use dvictorjhg\braidphp\Router\Http\Request;

#[Route(path: '/api')]
final class GreetingController
{
    public function __construct(private Greeter $greeter)
    {
    }

    #[Get('/hello/:name', pathMatch: 'full')]
    public function hello(Request $request): string
    {
        return $this->greeter->greeting($request->getAttribute('name') ?? '');
    }
}
03

Declare the application module.

Import HttpModule to register Router::class explicitly, then register the provider and controller. You can also supply a configured Router through App providers.

src/AppModule.php

<?php

declare(strict_types=1);

namespace App;

use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Router\HttpModule;

#[Module(
    imports: [HttpModule::class],
    providers: [Greeter::class],
    controllers: [GreetingController::class],
)]
final class AppModule
{
}
04

Create the front controller and make a request.

The entry point follows the same boot sequence as Example/index.php: autoload, bootstrap the root module, then listen on SERVER_ADDRESS and SERVER_PORT with defaults.

index.php

<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use App\AppModule;
use dvictorjhg\braidphp\Core\App;

$app = new App();
$app->bootstrapModule(new AppModule());

$address = (string) getenv('SERVER_ADDRESS') ?: '0.0.0.0';
$port = (string) getenv('SERVER_PORT') ?: '8000';

$app->listen(address: $address, port: $port);
Terminal 1php index.php Terminal 2curl http://127.0.0.1:8000/api/hello/Ada
What should happen

Run the server in one terminal and the curl request in a second terminal. The server prints "Server listening on 0.0.0.0:8000..." and the request returns "Hello Ada!". Every extra request is handled by the same process in sequence.

03 / Modules

Use modules as the composition boundary.

A module is just the #[Module] attribute data. App::bootstrapModule() processes imports first, then providers, controllers, and bootstrap entries.

Example/AppModule.php and Example/Modules/* PHP
// Example/AppModule.php
<?php

declare(strict_types=1);

namespace dvictorjhg\braidphp\Example;

use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Example\Modules\GreeterModule;
use dvictorjhg\braidphp\Example\Modules\HealthModule;
use dvictorjhg\braidphp\Router\HttpModule;

#[Module(
    imports: [
        HttpModule::class,
        GreeterModule::class,
        HealthModule::class,
    ],
)]
class AppModule
{
}

// Example/Modules/GreeterModule.php
<?php

declare(strict_types=1);

namespace dvictorjhg\braidphp\Example\Modules;

use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Example\Controllers\GreeterComponent;
use dvictorjhg\braidphp\Example\Modules\GreeterProviderModule;

#[Module(
    imports: [GreeterProviderModule::class],
    controllers: [GreeterComponent::class],
)]
class GreeterModule
{
}

// Example/Modules/GreeterProviderModule.php
<?php

declare(strict_types=1);

namespace dvictorjhg\braidphp\Example\Modules;

use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Example\Providers\GreeterProvider;

#[Module(
    providers: [GreeterProvider::class],
)]
class GreeterProviderModule
{
}

// Example/Modules/HealthModule.php
<?php

declare(strict_types=1);

namespace dvictorjhg\braidphp\Example\Modules;

use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Example\Controllers\HealthComponent;
use dvictorjhg\braidphp\Example\Providers\HealthProvider;

#[Module(
    providers: [HealthProvider::class],
    controllers: [HealthComponent::class],
)]
class HealthModule
{
}
01
imports

Module classes or objects to bootstrap before the current module.

02
providers

An array or PHPInjector Container passed to a new Injector.

03
controllers

Class strings or objects scanned for public route methods. Actions are stored by class name; to reuse a prebuilt controller, also register it as a provider under that class name.

04
bootstrap

Keyed startup entries resolved after routes and providers are ready.

Ordering
  • imports are bootstrapped first, in container iteration order.
  • providers create a new injector whose parent is the previously active injector, so earlier imported providers stay visible unless a later identifier shadows them.
  • controllers are scanned only after the injector is ready.
  • bootstrap runs last; keyed class names are resolved through the injector, while existing objects are kept as-is.
Dependency injection boundary
  • HttpModule registers Router::class.
  • Controllers are invoked through PHPInjector\DI\Injector::inject().
  • Constructor dependencies can come from the current module or any imported module/provider chain.
  • Only controller classes/objects become routes; providers by themselves do not expose HTTP endpoints.
App constructor providers

Seed providers before the first module.

App accepts an array or Container in its constructor. Use it when infrastructure should exist before bootstrapModule() runs.

<?php

declare(strict_types=1);

use dvictorjhg\braidphp\Core\App;

require_once __DIR__ . '/vendor/autoload.php';

$app = new App([
    'env' => 'development',
]);
bootstrap example

Resolve startup services after routes exist.

Bootstrap entries are keyed by class name. Arrays become constructor arguments for that class, while prebuilt objects are left untouched.

<?php

declare(strict_types=1);

use dvictorjhg\braidphp\Core\App;
use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Router\HttpModule;

require_once __DIR__ . '/vendor/autoload.php';

final class BootstrapService
{
}

final class ExistingService
{
}

#[Module(
    imports: [HttpModule::class],
    bootstrap: [
        BootstrapService::class => [],
        ExistingService::class => new ExistingService(),
    ],
)]
final class StartupModule
{
}

$app = new App();
$app->bootstrapModule(new StartupModule());
Provider form Meaning in BraidPHP Example
Greeter::class Lazy class resolution through the injector. [Greeter::class]
Interface::class => Impl::class Alias one identifier to a concrete class string provider. [Formatter::class => HtmlFormatter::class]
Service::class => new Service(...) Inject an existing object exactly as supplied. [Clock::class => new SystemClock()]
'env' => 'prod' Store a named scalar or context value for explicit lookup or #[Inject] usage in PHPInjector. ['env' => 'production']
Container Use PHPInjector\Container\Container instead of a plain array when you need container semantics directly. new Container([...])
04 / Routing

Declare routes where the controller lives.

RouteScanner reads class and method attributes, Router walks the resulting tree depth-first, and App::handle() attaches the matched parameters to a request copy. Immutable route-path segments are reused across dispatches; request parameters and custom matcher results are never cached.

Example/Controllers/GreeterComponent.php ROUTES
<?php

namespace dvictorjhg\braidphp\Example\Controllers;

use dvictorjhg\braidphp\Router\Attributes\Get;
use dvictorjhg\braidphp\Router\Attributes\Route;
use dvictorjhg\braidphp\Router\Http\HttpMethod;
use dvictorjhg\braidphp\Router\Http\Request;
use dvictorjhg\braidphp\Router\Http\Response;

#[Route(path: '/api')]
final class GreeterComponent
{
    #[Route(
        httpMethod: HttpMethod::GET->value | HttpMethod::POST->value,
        path: '/hi/:name'
    )]
    public function hi(Request $request): string
    {
        $name = $request->getAttribute('name') ?? '';
        return "Hi $name!";
    }

    #[Get('/hello/:name')]
    public function greet(Request $request): string
    {
        $name = $request->getAttribute('name') ?? '';
        return 'Hello ' . $name . '!';
    }

    #[Get('/hello')]
    public function greetQueryParam(Request $request): Response
    {
        $name = $request->getQueryParams()['name'] ?? null;
        return \is_string($name) && $name !== ''
            ? new Response(body: 'Hello ' . $name . '!')
            : new Response(400);
    }
}
A request through the treeGET /api/hello/Ada
class prefix/api
method path/hello/:name
capture:name = Ada
RouteMatch -> request copy -> action
Query/api/hello?name=Ada

Use getQueryParams() for query strings; route params and query params are separate.

Path matchprefix / full

prefix is the default; full rejects leftover segments at that route level.

Supported HTTP method attributes

All nine shortcut attributes extend the generic Route attribute.

GET#[Get] HEAD#[Head] POST#[Post] PUT#[Put] DELETE#[Delete] CONNECT#[Connect] OPTIONS#[Options] TRACE#[Trace] PATCH#[Patch]
Matching behavior
  • Class-level #[Route(path: ...)] values are prefixes by default; set pathMatch: 'full' when that route level must reject leftover segments.
  • :name captures a decoded path segment and makes it available through Request::getAttribute().
  • Query strings are parsed from the URI into Request::getQueryParams().
  • Routes are checked in the order they were added to Router; the first matching branch wins.
  • A method can accept multiple HTTP verbs through the generic #[Route] attribute with a combined integer mask such as HttpMethod::GET->value | HttpMethod::POST->value, or by stacking distinct shortcut attributes such as #[Get] and #[Post].
Failure cases
  • No route match: App::handle() returns 404 Not Found.
  • Unsupported request method string: Router::processRoutes() throws InvalidArgumentException.
  • Invalid custom matcher result: the matcher must return UrlMatcherResult or null, otherwise RouterException is thrown.
  • Non-public methods with route attributes are ignored and emit a warning during scanning.
  • A class-level route without any method routes contributes no route entries.
Equivalent declarations

One GET route, two valid forms.

The #[Get] shortcut and generic #[Route] attribute resolve to the same GET route. Choose one declaration for a route.

#[Get('/hello/:name', pathMatch: 'full')]
public function hello(Request $request): string
{
    return 'Hello ' . ($request->getAttribute('name') ?? '') . '!';
}
#[Route(
    httpMethod: HttpMethod::GET,
    path: '/hello/:name',
    pathMatch: 'full',
)]
public function hello(Request $request): string
{
    return 'Hello ' . ($request->getAttribute('name') ?? '') . '!';
}
Do not stack both attributes

Stacking both on one method creates duplicate route entries for the same path and makes precedence harder to reason about.

Programmatic matcher

Return UrlMatcherResult or return null.

Programmatic routes can use a custom matcher instead of a path string, but not both at once.

<?php

declare(strict_types=1);

use dvictorjhg\braidphp\Router\Classes\Route;
use dvictorjhg\braidphp\Router\Classes\UrlMatcherResult;
use dvictorjhg\braidphp\Router\Http\HttpMethod;
use dvictorjhg\braidphp\Router\Http\Response;
use dvictorjhg\braidphp\Router\Router;

require_once __DIR__ . '/vendor/autoload.php';

final class HealthComponent
{
    public function status(): Response
    {
        return new Response(body: 'ok');
    }
}

$router = new Router();

$router->setRoutes(new Route(
    httpMethod: HttpMethod::GET,
    matcher: static function (array $parts, Route $route): ?UrlMatcherResult {
        return ($parts[0] ?? null) === 'health'
            ? new UrlMatcherResult(['health'])
            : null;
    },
    action: [HealthComponent::class, 'status'],
));

$matched = $router->processRoutes(new \dvictorjhg\braidphp\Router\Http\Request(
    method: HttpMethod::GET,
    uri: '/health',
));

echo $matched !== null ? 'matched' : 'not matched';
Expected output
matched
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');
Expected output
404 DENY

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 output
201 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.

StandardImplemented support
PSR-7Messages, server requests, responses, URIs, streams, and uploaded files.
PSR-11PHPInjector provides the container. App accepts its concrete Container, not arbitrary ContainerInterface implementations.
PSR-15App is a RequestHandlerInterface with ordered MiddlewareInterface registration.
PSR-17HttpFactory implements all six HTTP factory interfaces from psr/http-factory.
PSR-3App 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.
06 / Recipes

A JSON API without opening a socket.

Build a JSON endpoint with an injected service, named configuration, decoded path parameters, and query validation. Run this complete example from your project root after composer install; handle() lets you send requests without starting the listener.

A JSON API without opening a socket.PHP
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use dvictorjhg\braidphp\Core\App;
use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Router\Attributes\Get;
use dvictorjhg\braidphp\Router\Attributes\Route;
use dvictorjhg\braidphp\Router\Http\HttpMethod;
use dvictorjhg\braidphp\Router\Http\Request;
use dvictorjhg\braidphp\Router\Http\Response;
use dvictorjhg\braidphp\Router\HttpModule;
use PHPInjector\DI\Attributes\Inject;

final class Profiles
{
    public function __construct(#[Inject('env')] private string $environment)
    {
    }

    public function response(string $name): Response
    {
        return new Response(
            headers: ['Content-Type' => 'application/json'],
            body: json_encode(['name' => $name, 'env' => $this->environment], JSON_THROW_ON_ERROR),
        );
    }
}

#[Route(path: '/api')]
final class ProfilesController
{
    public function __construct(private Profiles $profiles)
    {
    }

    #[Get('/users/:name', pathMatch: 'full')]
    public function user(Request $request): Response
    {
        return $this->profiles->response($request->getAttribute('name') ?? '');
    }

    #[Get('/users', pathMatch: 'full')]
    public function query(Request $request): Response
    {
        $name = $request->getQueryParams()['name'] ?? null;
        if (!is_string($name) || $name === '') {
            return new Response(400, ['Content-Type' => 'application/json'], '{"error":"name is required"}');
        }
        return $this->profiles->response($name);
    }
}

#[Module(
    imports: [HttpModule::class],
    providers: [Profiles::class, 'env' => 'test'],
    controllers: [ProfilesController::class],
)]
final class ProfilesModule
{
}

$app = new App();
$app->bootstrapModule(new ProfilesModule());
$request = new Request(method: HttpMethod::GET, uri: '/api/users/Ada%20Lovelace');
$response = $app->handle($request);
echo $response->getStatusCode() . ' ' . (string) $response->getBody() . PHP_EOL;
echo $response->getHeaderLine('Content-Type') . PHP_EOL;

foreach (['/api/users?name=', '/missing'] as $uri) {
    $response = $app->handle(new Request(method: HttpMethod::GET, uri: $uri));
    echo $response->getStatusCode() . ' ' . (string) $response->getBody() . PHP_EOL;
}
Expected output
200 {"name":"Ada Lovelace","env":"test"}
application/json
400 {"error":"name is required"}
404 Not Found

Action results are not automatically JSON

  • Actions may return any ResponseInterface; middleware may modify the response.
  • Null, scalars, native streams, PSR streams, and stringable objects become a 200 Response. Set your content type explicitly.
  • Arrays raise AppException; ordinary non-stringable objects fail stream conversion. Return json_encode() in a Response for JSON.
  • Direct handlers propagate exceptions unless middleware catches them. listen() logs uncaught application errors and attempts a generic 500 response; failed writes close the connection.

Test handlers without a server

In an application test, bootstrap your module, construct a Request, and pass it to App::handle(). Assert the returned response status, headers, and body. Include valid input, invalid input, and a missing route, as above. No port, web server, or curl process is needed.

The injector is globally active, not request scoped. Avoid request data in cached services and avoid bootstrapping unrelated applications in the same process.

07 / Runtime lifecycle

Follow the request from the socket to the controller result.

The native listener accepts and parses a connection, passes the request through middleware and routing, invokes the controller, and writes the response. Calling handle() directly uses the same middleware and dispatch steps without socket parsing or response emission.

01Acceptstream_socket_accept()
02ParseRequestParser::fromResource()
03MiddlewareApp::handle()
04MatchRouter::processRoutes()
05ResolveInjector::inject()
06WriteResponseEmitter::write()
01

Raw socket to Request

RequestParser uses HttpOptions for the total read deadline and header/body byte limits. Defaults are five seconds, 64 KiB of headers, and 8 MiB of body. Invalid or duplicate lengths, truncated bodies, and Transfer-Encoding are rejected. An empty client stream yields no request.

02

Routing and parameter capture

Router compares the request method against the HttpMethod enum, walks the registered routes in order, and collects decoded :name path parameters into RouteMatch::params.

03

Controller invocation

App runs middleware before routing, attaches matched path parameters as request attributes, and invokes the route action through PHPInjector. Request arguments are available by concrete class and PSR request interface; responses return through the middleware in reverse order.

04

Result conversion and failures

Any ResponseInterface enters response middleware unchanged; other supported results become Response(200, [], body). Arrays raise AppException; non-stringable objects fail body conversion. The listener logs application errors and attempts a generic 500. ResponseEmitter buffers the body and full HTTP payload before writing. Its five-second default writeTimeout covers socket writes after serialization, not controller execution or body conversion. Write failures are logged and the connection closes.

Listen with explicit address and portBLOCKING
<?php

declare(strict_types=1);

use dvictorjhg\braidphp\Core\App;
use dvictorjhg\braidphp\Core\Attributes\Module;
use dvictorjhg\braidphp\Router\HttpModule;

require_once __DIR__ . '/vendor/autoload.php';

#[Module(imports: [HttpModule::class])]
final class RuntimeModule
{
}

$app = new App();
$app->bootstrapModule(new RuntimeModule());
$app->listen(
    address: '0.0.0.0',
    port: '8000',
);

Use a process manager, reverse proxy, or container platform when the application needs more than one worker.

404
No matching route

App::handle() returns a plain Not Found response.

500
Unhandled throwable

The native listener logs application exceptions and attempts 500 Internal Server Error without exposing details. Malformed input triggers an attempted 400 Bad Request. If response writing fails, the connection closes without a replacement response.

08 / Operations

Configure the server, then choose how to run it.

The repository ships both direct PHP entry points and container-oriented workflows for development and production images.

Environment variables
  • SERVER_ADDRESS: defaults to 0.0.0.0 in Example/index.php.
  • SERVER_PORT: defaults to 8000 and is published by both container workflows.
  • ENVIRONMENT, APP_PATH, and DOCKER_IMAGE_TAG configure the target, application path, and image label.

Create a local .env at the repository root before either container command. These values select development, not production deployment. Compose forwards .env to the container; the Podman helpers only set selected variables and do not forward XDEBUG_MODE from that file.

ENVIRONMENT=development
APP_PATH=/app
SERVER_ADDRESS=0.0.0.0
SERVER_PORT=8000
DOCKER_IMAGE_TAG=php-8.5.12-cli-trixie
Deployment guidance
  • Use php Example/index.php or your own front controller for direct local runs.
  • Because the runtime is single-process and blocking, scale by running multiple container or process instances behind a reverse proxy or platform load balancer.
  • The repository Docker image uses PHP 8.5.12; the package requires PHP ~8.4.27 || ^8.5.12.
  • Do not expect long-running concurrent workloads to be multiplexed inside one BraidPHP listener process.

Per-application HTTP options

Pass immutable HttpOptions to App or directly to RequestParser::fromResource(). Sizes are bytes, deadlines are finite positive seconds, and backlog is a positive socket queue size. Defaults are 65536 header bytes, 8388608 body bytes, five seconds for each deadline, and backlog 128. Zero body bytes rejects nonempty bodies. Invalid options throw InvalidArgumentException.

HttpOptionsPHP
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use dvictorjhg\braidphp\Core\App;
use dvictorjhg\braidphp\Router\Http\HttpOptions;
use dvictorjhg\braidphp\Router\Http\RequestParser;

$options = new HttpOptions(
    maxHeaderBytes: 131_072,
    maxBodyBytes: 16_777_216,
    readTimeout: 10.0,
    writeTimeout: 10.0,
    backlog: 256,
);
$app = new App(httpOptions: $options);
$stream = fopen('php://temp', 'w+');
fwrite($stream, "POST / HTTP/1.1\r\nContent-Length:4\r\n\r\ndata");
rewind($stream);
try {
    $request = RequestParser::fromResource($stream, $options);
    echo (string) $request?->getBody();
} finally {
    fclose($stream);
}
Expected output
data
Docker / Compose

Use the checked-in image definition.

docker-compose.yml builds docker/php/php.Dockerfile, passes APP_PATH and ENVIRONMENT, exposes SERVER_PORT, and mounts src/, Example/, tests/, coverage/, and debug/.

docker compose up --build php
Podman helpers

Use the repository scripts when Podman is your container runtime.

bin/podman-run.sh and bin/podman-run.ps1 both read .env, build the selected target from docker/php/php.Dockerfile, create debug/ and coverage/, publish SERVER_PORT, and mount source directories in development mode.

./bin/podman-run.sh --environment development --detach
podman exec braidphp-development composer test
./bin/podman-run.sh --action down
Package install versus repository clone

Clone the repository to run the bundled Example application and container workflows. For a Composer-installed application, create your own entry point and modules as shown in First application; do not depend on Example files being installed with the package.

Public listener limitations

This is a minimal HTTP listener, not a hardened edge server. TLS, worker supervision, and rate limiting need an external boundary. Configure byte limits, read/write deadlines, and backlog with HttpOptions. Chunked requests are rejected and persistent connections are not provided. HEAD does not automatically suppress the body. Supported verbs without a route return 404, not 405. Methods outside HttpMethod raise a routing exception; without catching middleware, the listener logs it and attempts a generic 500 rather than 501.

09 / Development

Test and contribute to BraidPHP.

When working on the framework itself, install the development dependencies, then check types, coding standards, tests, and coverage. Application tests can call handlers directly without starting the listener.

CommandsCLI
php tools/check-docs.php
composer validate --strict
composer check-platform-reqs
composer analyse
composer check-style
composer test
composer test:coverage
composer coverage:check

Run these commands from a repository checkout after composer install. The documentation check needs PHP DOM and proc_open; coverage needs Xdebug or PCOV.

Forward PHPUnit filters with composer test -- --filter AppTest. Override the coverage report and threshold with composer coverage:check -- build/test-results/clover.xml 90. PHPStan, PHPUnit, and PHP_CodeSniffer accept custom --configuration or --standard paths. Runtime options are independent of these development tools.