Request handlers

Write a handler

Save this as server.php next to your application’s vendor/ directory. A CallbackRequestHandler receives the request and returns a response. Pass it to ServerCommand to reuse the server’s JSON configuration and worker lifecycle.

PHP
<?php
require __DIR__.'/vendor/autoload.php';

use M4W\WebServer\Cli\ServerCommand;
use M4W\WebServer\Http\CallbackRequestHandler;
use M4W\WebServer\Http\Request;
use M4W\WebServer\Http\Response;

$handler = new CallbackRequestHandler(
    static fn (Request $request): Response => Response::json([
        'method' => $request->method,
        'uri' => $request->uri,
    ])
);

exit((new ServerCommand)->run($argv, $handler));

Stop any example server using port 8080, then run php server.php. In a second terminal, request curl http://127.0.0.1:8080/hello. The response contains {"method":"GET","uri":"/hello"}. You can pass a profile as php server.php server.json.

Read request bodies

$request->body->readAll(1_048_576) reads the remaining bytes with a 1 MiB ceiling and rejects overflow. To process chunks, use the following inside the callback. A read returns a nonempty string or null at EOF. The body has one consumer and moves forward only.

PHP
$hash = hash_init('sha256');
while (($chunk = $request->body->read(16384)) !== null) {
    hash_update($hash, $chunk);
}
return Response::json(['sha256' => hash_final($hash)]);

Consume required input before returning. For multipart input, $request->multipart() provides fields and temporary upload streams. Copy files you need into application storage and close the form in a finally block.

Send a response

Response::json($data, $status) encodes an array and sets the JSON content type. Response::text($body, $status, $headers) accepts a string and optional response headers. Both default to status 200. For large output, pass a readable body to the Response constructor. A producer receives a byte allowance for each call and returns null at EOF.

The transport closes response bodies on completion or cancellation. Put resource cleanup in the body’s close callback. A handler error before response commitment can produce a generic 500. A failure after commitment aborts the exchange.

Request state

Read metadata from the Request object. Each managed request starts with empty input superglobals. Mini4Work saves supported request globals when a managed Fiber suspends and restores them when it resumes. Static properties, shared objects and process-wide settings persist in the worker. Keep user-specific state local to the request.

Blocking database calls, filesystem operations and CPU work occupy their worker. Account for that when choosing the size of the worker pool.