Nexus API Reference

HttpApp
in package

FinalYes

Fluent DSL entry point for building a Nexus HTTP application.

HttpApp is mutable during construction: you register routes, actors, middleware, and exception mappers by chaining method calls. The terminal HttpApp::compile() operation freezes the DSL state into an immutable CompiledHttpApp that implements PSR-15 RequestHandlerInterface and is ready to be handed to a Swoole or Fiber HTTP server adapter.

HttpApp itself does NOT implement RequestHandlerInterface. The separation of "building" from "serving" keeps the hot-path handler allocation cost in the server adapter rather than here. The first compile() call freezes the DSL: repeated compiles are idempotent (reusing the frozen state and the live actor table), and any further mutation throws HttpAppAlreadyCompiledException.

Example — minimal JSON API:

$app = HttpApp::create($system)
    ->get('/users/{id}', UserHandler::class)
    ->middleware(AuthenticationMiddleware::class);

$app->post('/users', UserHandler::class)
    ->name('user.create');

$compiled = $app->compile();
// Hand $compiled to SwooleHttpServer or similar adapter.

Example — actor-backed route (inject the actor via #[FromActor]):

$app = HttpApp::create($system)
    ->actor('orders', Props::fromBehavior($orderBehavior))
    ->post('/orders', static function (
        ServerRequestInterface $request,
        #[FromActor('orders')] ActorRef $orders,
    ): ResponseInterface {
        $orders->tell(new PlaceOrder(...));

        return Response::accepted();
    });
Tags
see
CompiledHttpApp

The immutable PSR-15 handler produced by compile()

RouteBuilder

Fluent per-route configuration (middleware, name)

WsApplication

Decorator that adds WebSocket DSL on top of HttpApp

psalm-api

Table of Contents

Methods

actor()  : ActorRegistration
Register a long-lived actor shared across all requests on this worker.
clearRouteCache()  : void
Evict all entries from the route cache configured via {@see withRouteCache()}.
compile()  : CompiledHttpApp
Freeze the DSL state into an immutable, ready-to-serve CompiledHttpApp.
create()  : self
Create a new HttpApp DSL instance tied to the given actor system.
delete()  : RouteBuilder
Register a DELETE route.
discover()  : self
Scan a directory for classes annotated with route attributes and register them automatically.
errorMode()  : self
Set the error-reporting mode for the built-in exception-handler middleware.
get()  : RouteBuilder
Register a GET route.
group()  : RouteGroup
Register a group of routes sharing a common path prefix.
middleware()  : self
Append a PSR-15 middleware to the global stack applied to every request.
onException()  : self
Register a custom exception-to-response mapper for a specific exception type.
paramResolver()  : self
Register a custom handler-parameter resolver.
patch()  : RouteBuilder
Register a PATCH route.
perRequestActor()  : ActorRegistration
Register a per-request actor that is spawned fresh for each incoming request.
post()  : RouteBuilder
Register a POST route.
put()  : RouteBuilder
Register a PUT route.
registeredRoutes()  : array<int, RouteSummary>
Snapshot of every route registered so far — both the ones already promoted into the route collection (via attribute discovery or by a prior `compile()`) and the ones still queued in pending builders.
requiresPoolSingleton()  : bool
Return `true` if any registered actor uses the `PoolSingleton` mode.
withMessageSerializer()  : self
Attach a message serializer used when actor-backed routes need to encode request payloads as actor messages across worker boundaries.
withoutDefaultExceptionHandler()  : self
Disable the built-in exception-handler middleware.
withPoolSingletonSpawner()  : self
Supply the spawner used to boot `PoolSingleton` actors.
withRouteCache()  : self
Enable PSR-16 route caching to avoid re-parsing attribute routes on each boot.

Methods

actor()

Register a long-lived actor shared across all requests on this worker.

public actor(string $name, Props $props) : ActorRegistration

The actor is spawned once per worker process when compile() is called and remains alive for the lifetime of the worker. Handlers and middleware receive the actor by declaring a parameter attributed with #[FromActor('name')].

Parameters
$name : string

Unique actor name within this app.

$props : Props

Actor spawn configuration.

Return values
ActorRegistration

Fluent configuration (e.g. set actor mode).

clearRouteCache()

Evict all entries from the route cache configured via {@see withRouteCache()}.

public clearRouteCache() : void

Useful during deployment or when routes change at runtime. A no-op if no cache has been configured.

compile()

Freeze the DSL state into an immutable, ready-to-serve CompiledHttpApp.

public compile() : CompiledHttpApp

The first call is terminal: routes, actors, middleware, and configuration are frozen, and worker-local/pool-singleton actors are spawned exactly once. Repeated calls are idempotent — they reuse the frozen state and the live actor table and return an equivalent CompiledHttpApp. Mutating the DSL after compile() throws HttpAppAlreadyCompiledException.

Return values
CompiledHttpApp

create()

Create a new HttpApp DSL instance tied to the given actor system.

public static create(ActorSystem $system[, ContainerInterface|null $container = null ][, EventDispatcherInterface|null $events = null ][, LoggerInterface|null $logger = null ]) : self
Parameters
$system : ActorSystem

The running actor system (used to spawn actor-backed routes).

$container : ContainerInterface|null = null

PSR-11 container for resolving handler and middleware class names.

$events : EventDispatcherInterface|null = null

PSR-14 dispatcher; emits RequestStarted and RequestCompleted.

$logger : LoggerInterface|null = null

PSR-3 logger forwarded to the exception-handler middleware.

Return values
self

delete()

Register a DELETE route.

public delete(string $path, string|Closure $handler) : RouteBuilder
Parameters
$path : string

URI path (may contain {param} placeholders).

$handler : string|Closure

Handler class name or inline closure.

Return values
RouteBuilder

Fluent builder for per-route middleware and naming.

discover()

Scan a directory for classes annotated with route attributes and register them automatically.

public discover(string $directory) : self

Discovered routes are merged into the route collection on the first compile() call. May be called multiple times to add more directories.

Parameters
$directory : string

Absolute path to scan recursively for PHP classes.

Return values
self

errorMode()

Set the error-reporting mode for the built-in exception-handler middleware.

public errorMode(ErrorMode $mode) : self

ErrorMode::Production (default) returns opaque 500 responses. ErrorMode::Development includes stack traces in the response body.

Parameters
$mode : ErrorMode

The desired error verbosity mode.

Return values
self

get()

Register a GET route.

public get(string $path, string|Closure $handler) : RouteBuilder
Parameters
$path : string

URI path (may contain {param} placeholders).

$handler : string|Closure

Handler class name or inline closure.

Return values
RouteBuilder

Fluent builder for per-route middleware and naming.

group()

Register a group of routes sharing a common path prefix.

public group(string $prefix, callable(RouteGroup): void $register) : RouteGroup

The $register closure receives a RouteGroup instance on which you call the same get(), post(), etc. methods. All routes defined inside the closure are committed to this HttpApp when group() returns.

Parameters
$prefix : string

Common URI prefix for all routes in the group.

$register : callable(RouteGroup): void

Closure that defines routes on the group.

Return values
RouteGroup

middleware()

Append a PSR-15 middleware to the global stack applied to every request.

public middleware(string|MiddlewareInterface $middleware) : self

Middleware is applied in registration order, before per-route middleware. Pass a class name string when using a PSR-11 container, or a concrete MiddlewareInterface instance for inline middleware.

Parameters
$middleware : string|MiddlewareInterface

Class name or middleware instance.

Return values
self

onException()

Register a custom exception-to-response mapper for a specific exception type.

public onException(TException> $exceptionClass, callable(TException, ServerRequestInterface): ResponseInterface $mapper) : self

User-registered mappers take precedence over the built-in default mappers. If the built-in exception handler is disabled via withoutDefaultExceptionHandler(), this method has no effect unless you add your own ExceptionHandlerMiddleware.

Parameters
$exceptionClass : TException>

Exception class to handle.

$mapper : callable(TException, ServerRequestInterface): ResponseInterface

Converts the exception to an HTTP response.

Tags
template
Return values
self

paramResolver()

Register a custom handler-parameter resolver.

public paramResolver(ParamResolver $resolver[, bool $override = false ]) : self

Custom resolvers are appended after all built-in resolvers by default. Pass true for $override to prepend the resolver so it takes priority over the built-in ones.

Parameters
$resolver : ParamResolver

The custom resolver to add.

$override : bool = false

When true, prepend instead of append.

Return values
self

patch()

Register a PATCH route.

public patch(string $path, string|Closure $handler) : RouteBuilder
Parameters
$path : string

URI path (may contain {param} placeholders).

$handler : string|Closure

Handler class name or inline closure.

Return values
RouteBuilder

Fluent builder for per-route middleware and naming.

perRequestActor()

Register a per-request actor that is spawned fresh for each incoming request.

public perRequestActor(string $name, Props $props) : ActorRegistration

The actor is stopped automatically after the request handler returns. Useful for request-scoped stateful logic (e.g. a saga or command handler).

Parameters
$name : string

Unique actor name within this app.

$props : Props

Actor spawn configuration.

Return values
ActorRegistration

Fluent configuration.

post()

Register a POST route.

public post(string $path, string|Closure $handler) : RouteBuilder
Parameters
$path : string

URI path (may contain {param} placeholders).

$handler : string|Closure

Handler class name or inline closure.

Return values
RouteBuilder

Fluent builder for per-route middleware and naming.

put()

Register a PUT route.

public put(string $path, string|Closure $handler) : RouteBuilder
Parameters
$path : string

URI path (may contain {param} placeholders).

$handler : string|Closure

Handler class name or inline closure.

Return values
RouteBuilder

Fluent builder for per-route middleware and naming.

registeredRoutes()

Snapshot of every route registered so far — both the ones already promoted into the route collection (via attribute discovery or by a prior `compile()`) and the ones still queued in pending builders.

public registeredRoutes() : array<int, RouteSummary>

Intended for index pages, smoke tests, and admin/debugging tooling. Returns immutable RouteSummary value objects so callers don't couple to the internal Route shape.

Return values
array<int, RouteSummary>

requiresPoolSingleton()

Return `true` if any registered actor uses the `PoolSingleton` mode.

public requiresPoolSingleton() : bool

Server adapters inspect this flag to decide whether to boot a shared singleton coordinator before starting request workers.

Return values
bool

withMessageSerializer()

Attach a message serializer used when actor-backed routes need to encode request payloads as actor messages across worker boundaries.

public withMessageSerializer(MessageSerializer $serializer) : self
Parameters
$serializer : MessageSerializer

The serializer to use.

Return values
self

withoutDefaultExceptionHandler()

Disable the built-in exception-handler middleware.

public withoutDefaultExceptionHandler() : self

Use this when you want full control over exception handling, e.g. when integrating with a framework that supplies its own error-handling layer.

Return values
self

withPoolSingletonSpawner()

Supply the spawner used to boot `PoolSingleton` actors.

public withPoolSingletonSpawner(PoolSingletonSpawner $spawner) : self

Called automatically by server adapters that support the singleton pool mode; application code rarely needs to call this directly.

Parameters
$spawner : PoolSingletonSpawner

The spawner implementation.

Return values
self

withRouteCache()

Enable PSR-16 route caching to avoid re-parsing attribute routes on each boot.

public withRouteCache(CacheInterface $cache[, string|null $key = null ]) : self

Closure-based routes are always excluded from the cache because closures cannot be serialised. They are re-added from the live route collection on every cache hit.

Parameters
$cache : CacheInterface

PSR-16 simple-cache implementation.

$key : string|null = null

Custom cache key; defaults to 'nexus.http.routes'.

Return values
self
On this page

Search results