phasync
Request handlers / RequestHandler

Class

RequestHandler

What an application's swerve.php returns: the callable that serves each HTTP exchange.

Introduction#

The callable gets a ClientRequest and returns when it is done: the response is then finished, and the connection serves its next request.

Class synopsis#

final class RequestHandler {
    /* Methods */
    public RequestHandler::__construct(Closure $handler)
}

Properties#

NameTypeDescription
$handlerreadonly Closure

Methods#

MethodDescription
__constructWrap the callable that serves each exchange.

Examples#

Example 1Hello, world
use Swerve\ClientRequest;
use Swerve\RequestHandler;

// swerve.php returns the handler; swerve calls it once for each request
$app = new RequestHandler(function (ClientRequest $request) {
    $request->sendResponseHeaders(200, ['content-type' => 'text/plain', 'content-length' => '13']);
    $request->write("Hello, world\n");
});                // returning ends the response; the connection serves its next request

if (debug_backtrace()) {
    return $app;   // swerve loads this file: it is the application's swerve.php
}

// Run directly: serve the application with swerve, and send it requests
require __DIR__ . '/../serve.php';
serve(__FILE__, ["GET / HTTP/1.1\r\nHost: example\r\n\r\n"]);
Output
HTTP/1.1 200 OK
content-type: text/plain
Server: Swerve
Content-Length: 13
Connection: close

Hello, world
Example 2
// swerve.php
return new Swerve\RequestHandler(function (Swerve\ClientRequest $request) {
    $request->write("Hello, world\n");
});