Web

Reference for the Web module: match a request path to a handler with a two-pass router that also records named routes for reverse routing, read query parameters and headers off the request, build URLs, and make outbound HTTP requests with an optional database log.

This page is a pure reference. For how the framework fits together, see the Guide.

Classes
  • Web - build a URL from a base path and query parameters.
  • WebClient - make outbound GET and POST HTTP requests.
  • WebClientDatabase - log outbound web client requests and their responses to the database.
  • WebErrorNotFound - an exception for a 404 Not Found outcome.
  • WebOn - register callbacks that run when a route is hit.
  • WebQuery - read query-string parameters and request details.
  • WebRoute - path routing with terminals, parameters, method guards and named reverse routing.
  • WebRouteHeader - run a callback when a request header is present.
  • WebRouteQuery - run a callback when a query parameter is present or matches.

Web

Build a URL from a base path and a set of query parameters, url-encoding each name and value.

Functions
Url

Url

Web::Url(string $baseUrl, array $queryParams = []): string

Create a URL given a base path and set of query parameters.

NameTypeDescription
$baseUrlstringThe base path or URL.
$queryParamsarrayA map of query parameter name to value.

Returns string The URL, with a query string when parameters are given.

WebClient

Functions for making GET and POST requests to other servers, including a POST that decodes a JSON response.

Functions

Get

WebClient::Get(string $url): string

Make a GET request and return the response body.

NameTypeDescription
$urlstringThe URL to request.

Returns string The response body.

Post

WebClient::Post(string $url, mixed $data, Callable|null $optionalDecodeCallback = null): string

Make a POST request, sending the data as JSON. On error throws a suitable exception, such as WebErrorNotFound.

NameTypeDescription
$urlstringThe URL to request.
$datamixedThe data to send; encoded as JSON.
$optionalDecodeCallbackCallable|nullAn optional callback that receives the response string and returns a decoded value.

Returns string The response body, or the decoded callback result.

PostJson

WebClient::PostJson(string $url, mixed $data, Callable|null $optionalDecodeCallback = null): mixed

Make a POST that expects JSON in return; the response is JSON decoded then passed through an optional decode callback.

NameTypeDescription
$urlstringThe URL to request.
$datamixedThe data to send; encoded as JSON.
$optionalDecodeCallbackCallable|nullAn optional callback applied to the decoded JSON, for example a FromJSON function.

Returns mixed The decoded response.

WebClientDatabase

Log outbound web client requests and their responses to the web_client_log table, recording verb, url, bodies, headers, timing and status.

Constants

ConstantValueDescription
WebClientDatabase::LOG_STATUS_IN_PROGRESS0The request has been recorded but not yet completed.
WebClientDatabase::LOG_STATUS_SUCCESS1The request completed and a response was recorded.
WebClientDatabase::LOG_STATUS_ERROR2The request failed.

AddError

WebClientDatabase::AddError(int $logId, float $durationMs, string|null $errorMessage = null): void

Update a web client log entry with error information.

NameTypeDescription
$logIdintThe id of the log entry to update.
$durationMsfloatThe duration in milliseconds before it failed.
$errorMessagestring|nullOptional error message to store in the response body.

Returns void

AddRequest

WebClientDatabase::AddRequest(string $verb, string $url, string $requestBody, array|null $requestHeaders = null): int

Log a new web client request to the database.

NameTypeDescription
$verbstringThe HTTP verb, such as GET, POST, PUT or DELETE.
$urlstringThe URL being requested.
$requestBodystringThe request body content.
$requestHeadersarray|nullThe request headers as an array.

Returns int The id of the created log entry.

AddResponse

WebClientDatabase::AddResponse(int $logId, int $responseCode, string $responseBody, float $durationMs, array|null $responseHeaders = null): void

Update a web client log entry with successful response data.

NameTypeDescription
$logIdintThe id of the log entry to update.
$responseCodeintThe HTTP response code, such as 200, 404 or 500.
$responseBodystringThe response body content.
$durationMsfloatThe duration of the request in milliseconds.
$responseHeadersarray|nullThe response headers as an array.

Returns void

WebErrorNotFound

An exception representing a 404 Not Found outcome, thrown by the web client and caught by the router. Extends Exception with message Not Found and code 404.

Functions

__construct

new WebErrorNotFound()

Create the exception with message Not Found and code 404.

Returns WebErrorNotFound

WebOn

Register callbacks that run whenever a route is hit. The registered callbacks are held in the public $hitCallbacks array and invoked by the router.

Functions
Hit

Hit

WebOn::Hit(callable $callback): void

Register a callback to run each time a route is hit.

NameTypeDescription
$callbackcallableThe callback to run on a route hit.

Returns void

WebQuery

Read values from the request query string, with typed and optional variants, the caller's IP address, and the decoded JSON request body.

ID

WebQuery::ID(string $parameter, int $defaultValue = 0)

Read a query parameter as an id, or the default when it is not set.

NameTypeDescription
$parameterstringThe query parameter name.
$defaultValueintThe value to use when the parameter is not set.

Returns The id value.

IntOptional

WebQuery::IntOptional(string $parameter): int|null

Read a query parameter as an integer, or null when it is not set.

NameTypeDescription
$parameterstringThe query parameter name.

Returns int|null The integer value, or null.

IPAddress

WebQuery::IPAddress(): string

The caller's IP address, taking a client or forwarded header when present, otherwise the remote address.

Returns string The IP address.

PostJSON

WebQuery::PostJSON(): stdClass

Read the raw request body and decode it as JSON.

Returns stdClass The decoded request body.

String

WebQuery::String(string $parameter, string $defaultValue = '')

Read a query parameter as a string, or the default when it is not set.

NameTypeDescription
$parameterstringThe query parameter name.
$defaultValuestringThe value to use when the parameter is not set.

Returns The string value.

StringOptional

WebQuery::StringOptional(string $parameter): string|null

Read a query parameter as a string, or null when it is not set.

NameTypeDescription
$parameterstringThe query parameter name.

Returns string|null The string value, or null.

WebRoute

Match a request path to a handler. It walks the requested path bit by bit through nested directories, terminals, parameters and request-method guards, rendering the first match. The same route definition also runs in a scan pass that records named routes so their paths can be looked up for reverse routing.

Constants

ConstantValueDescription
WebRoute::MODE_RENDER'render'The default mode: match the request URL and render the hit page.
WebRoute::MODE_SCAN'scan'Walk every directory to record named-route anchors and render nothing.

Check

WebRoute::Check(bool $condition, callable $uiCallback, ...$args): void

Match when a condition is true, calling the callback to output content.

NameTypeDescription
$conditionboolThe condition that must be true to match.
$uiCallbackcallableThe callback that outputs content.
...$argsArguments passed to the callback.

Returns void

Current

WebRoute::Current(): string

The path matched so far, from the parts consumed up to the current position.

Returns string The current path.

Default

WebRoute::Default(callable $uiCallback): void

Match unconditionally when nothing has matched yet, calling the callback.

NameTypeDescription
$uiCallbackcallableThe callback that outputs content.

Returns void

Delete

WebRoute::Delete(callable $handler): void

Match at the end of the path when the request method is DELETE, invoking the handler with no arguments.

NameTypeDescription
$handlercallableThe handler to invoke.

Returns void

Dir

WebRoute::Dir(string $name, callable $routeCallback, ...$args): void

Match the next part or parts of the requested path, descending into the callback. A name containing a slash is matched as several parts.

NameTypeDescription
$namestringThe path part to match, or empty to always match.
$routeCallbackcallableThe nested routing callback.
...$argsArguments passed to the callback.

Returns void

Error

WebRoute::Error(int $statusCode, callable $errorCallback): void

Handle the case where no route matched: set the HTTP response code and call the error callback.

NameTypeDescription
$statusCodeintThe HTTP status code, such as 404 or 500.
$errorCallbackcallableThe callback that renders the error page.

Returns void

File

WebRoute::File(string $name, callable $uiCallback, ...$args): void

Match all the way to the end of the requested path under a name, then call the callback to output content.

NameTypeDescription
$namestringThe path part to match.
$uiCallbackcallableThe callback that outputs content.
...$argsArguments passed to the callback.

Returns void

Filename

WebRoute::Filename(string $fileExtension, callable $routeCallback, ...$args): void

Match a path part ending in the given file extension, passing the filename without the extension to the callback.

NameTypeDescription
$fileExtensionstringThe file extension to match, without the leading dot.
$routeCallbackcallableThe callback, receiving the filename without its extension.
...$argsArguments passed to the callback.

Returns void

Get

WebRoute::Get(callable $handler): void

Match at the end of the path when the request method is GET, invoking the handler with no arguments.

NameTypeDescription
$handlercallableThe handler to invoke.

Returns void

GetNamed

WebRoute::GetNamed(string $name, array $params = []): string

The path recorded for a named route during the scan pass, with any placeholders substituted from the params. Throws when the name was not discovered.

NameTypeDescription
$namestringThe named route to look up.
$paramsarrayValues substituted into placeholders in the path.

Returns string The recorded path.

HasNamed

WebRoute::HasNamed(string $name): bool

Whether a named route was discovered during the scan pass.

NameTypeDescription
$namestringThe named route to check.

Returns bool True when the name is known.

hitEvent

WebRoute::hitEvent(): void

Run every callback registered with WebOn::Hit. Called by the router when a route is hit.

Returns void

Index

WebRoute::Index(callable $uiCallback, ...$args): void

Match the current path with no further name, as the index of the enclosing directory.

NameTypeDescription
$uiCallbackcallableThe callback that outputs content.
...$argsArguments passed to the callback.

Returns void

Integer

WebRoute::Integer(callable $routeCallback, ...$args): void

Match the next path part when it is an integer, passing the integer to the callback. Skipped during the scan pass.

NameTypeDescription
$routeCallbackcallableThe callback, receiving the parsed integer.
...$argsArguments passed to the callback.

Returns void

IsScanning

WebRoute::IsScanning(): bool

Whether routing is currently running in the scan pass.

Returns bool True during a scan.

Named

WebRoute::Named(string $name, ?callable $callback = null, ...$args): void

Wrap the routing for an addressable page under a name. In the scan pass it records the name and current path; in the render pass it just calls the callback.

NameTypeDescription
$namestringThe route name for reverse routing.
$callback?callableThe routing callback for the render pass.
...$argsArguments passed to the callback.

Returns void

Patch

WebRoute::Patch(callable $handler): void

Match at the end of the path when the request method is PATCH, decoding the body as JSON or form data and passing a stdClass to the handler.

NameTypeDescription
$handlercallableThe handler, receiving the decoded request.

Returns void

Peek

WebRoute::Peek(): string|null

The next path part without consuming it, or null when at the end of the path.

Returns string|null The next path part, or null.

Post

WebRoute::Post(callable $handler): void

Match at the end of the path when the request method is POST, decoding the body as JSON or form data and passing a stdClass to the handler.

NameTypeDescription
$handlercallableThe handler, receiving the decoded request.

Returns void

Put

WebRoute::Put(callable $handler): void

Match at the end of the path when the request method is PUT, decoding the body as JSON or form data and passing a stdClass to the handler.

NameTypeDescription
$handlercallableThe handler, receiving the decoded request.

Returns void

Redirect

WebRoute::Redirect(string $name, string $url): void

Match all the way to the end of the requested path under a name, then redirect to the given URL.

NameTypeDescription
$namestringThe path part to match.
$urlstringThe URL to redirect to.

Returns void

Scan

WebRoute::Scan(callable $routes): void

Run a route definition in scan mode to populate the name-to-path map, as the first pass before the render pass over the same routes.

NameTypeDescription
$routescallableThe route definition to scan.

Returns void

String

WebRoute::String(callable $routeCallback, ...$args): void

Match the next path part as a string, passing it to the callback. Skipped during the scan pass.

NameTypeDescription
$routeCallbackcallableThe callback, receiving the path part.
...$argsArguments passed to the callback.

Returns void

Ui

WebRoute::Ui(callable $routeCallback): void

Buffer the output of a routing callback, flushing it only when a match occurred and discarding it otherwise.

NameTypeDescription
$routeCallbackcallableThe routing callback whose output is buffered.

Returns void

WebRouteHeader

Run a callback when a request header is present, passing its value.

Functions

String

WebRouteHeader::String(string $headerName, callable $callback): void

Execute the callback with the header value when the header exists and is a non-empty string.

NameTypeDescription
$headerNamestringThe header name as it appears in the server variables, such as HTTP_X_QUEUE_ADMIN_TOKEN.
$callbackcallableThe callback, receiving the header value as a string.

Returns void

WebRouteQuery

Run a callback when a query parameter is present, either matching an exact value or passing its string value.

Functions

Exactly

WebRouteQuery::Exactly(string $parameter, string $expectedValue, callable $callback): void

Execute the callback when a query parameter exists with the exact value, or when it exists at all if the expected value is an empty string.

NameTypeDescription
$parameterstringThe query parameter name.
$expectedValuestringThe expected value; an empty string means the parameter only needs to exist.
$callbackcallableThe callback to execute on a match.

Returns void

String

WebRouteQuery::String(string $parameter, callable $callback): void

Execute the callback with the parameter value when the query parameter exists and has a non-empty string value.

NameTypeDescription
$parameterstringThe query parameter name.
$callbackcallableThe callback, receiving the parameter value as a string.

Returns void