Skip to content

Routing

Routes connect an HTTP method and a path to the code that answers it. PAM applications route with Nimbus (pushinbr/nimbus), the API-first framework that pam init --template api installs. Its router is compiled once when the worker boots and then reused for every request, so matching a route costs a hash lookup for static paths and a bounded regular expression for dynamic ones.

A new API project keeps its routes in routes.php. The file receives the router as $router:

routes.php
<?php
declare(strict_types=1);
use App\Controllers\PingController;
use Nimbus\RouteRegistrar;
/** @var RouteRegistrar $router */
$router->get('api/ping', [PingController::class, 'show']);
$router->get('/greeting', fn () => 'Hello World');

bootstrap/app.php builds the application and loads that file; index.php starts the listener:

bootstrap/app.php
<?php
declare(strict_types=1);
use Nimbus\App;
$app = new App();
$app->routes(dirname(__DIR__) . '/routes.php');
return $app;
index.php
<?php
declare(strict_types=1);
/** @var \Nimbus\App $app */
$app = require __DIR__ . '/bootstrap/app.php';
$app->listen((int) (getenv('PAM_PORT') ?: 3000));

Start the development server and call the route:

Terminal window
pam dev
Terminal window
$ curl http://127.0.0.1:3000/greeting
Hello World

A leading slash is optional: api/ping and /api/ping register the same route. A trailing slash in the request is ignored, so /greeting/ matches too.

The router has one method per HTTP verb:

$router->get($path, $handler);
$router->post($path, $handler);
$router->put($path, $handler);
$router->patch($path, $handler);
$router->delete($path, $handler);
$router->head($path, $handler);
$router->options($path, $handler);

On the App itself, $app->route('PURGE', '/cache', $handler) registers any other method.

A handler can be:

  • a closure;
  • a [Controller::class, 'method'] pair;
  • the class name of an invokable controller (a class with __invoke()).
routes.php
use App\Controllers\ProductController;
use App\Controllers\ShowDashboard;
$router->get('/health', fn () => ['status' => 'ok']);
$router->get('/products', [ProductController::class, 'index']);
$router->get('/dashboard', ShowDashboard::class);

Whatever the handler returns becomes the response:

Return value Response
Pam\Http\Response Sent as is.
A Responsable (such as a JsonResource or Redirect) Its toResponse() result.
An array or JsonSerializable JSON with application/json; charset=utf-8, keeping any status a middleware set.
A string or number A text/plain body.
null Whatever was written to the injected $response.

See Responses for the details.

Closure parameters are resolved by the container. Type-hint Request and Response to receive the current request and response, any class to receive an instance from the container, and use a route parameter name to receive its value:

use Pam\Http\Request;
use Psr\Log\LoggerInterface;
$router->get('/search', function (Request $request, LoggerInterface $logger): array {
$logger->info('Search for {term}', ['term' => $request->getQuery('q', '')]);
return ['q' => $request->getQuery('q', '')];
});

A closure that declares only (Request $request, Response $response) skips the container entirely, which is the fastest path.

Capture a path segment with braces. The value is passed to the parameter of the same name:

$router->get('/posts/{post}/comments/{comment}', fn (string $post, string $comment) => [
'post' => $post,
'comment' => $comment,
]);
Terminal window
$ curl http://127.0.0.1:3000/posts/1/comments/2
{"post":"1","comment":"2"}

You can also read parameters from the request:

use Pam\Http\Request;
use Pam\Http\Response;
$router->get('/users/{id}', function (Request $request, Response $response): Response {
return $response->json(['id' => $request->route('id')]);
});

Some rules to keep in mind:

  • A parameter fills an entire segment: /users/{id} works, /users/user-{id} throws when the route is registered.
  • Values are URL-decoded strings. Cast them yourself ((int) $id) or use a constraint so that only digits match.
  • Parameter names must be unique within a path and start with a letter or underscore.

Nimbus has no optional parameter syntax. Register two routes that share a handler instead:

$listPosts = fn (?string $category = null) => ['category' => $category ?? 'all'];
$router->get('/posts', $listPosts);
$router->get('/posts/{category}', $listPosts);

Use where() to restrict what a parameter matches. Pass a Nimbus\RouteConstraint case or your own pattern (without delimiters):

use Nimbus\RouteConstraint;
$router->get('/users/{id}', [UserController::class, 'show'])
->where('id', RouteConstraint::Integer);
$router->get('/orders/{reference}', [OrderController::class, 'show'])
->where('reference', '[A-Z]{3}-[0-9]{6}');
Constraint Pattern
RouteConstraint::Integer [0-9]+
RouteConstraint::Uuid RFC 4122 UUID, versions 1 to 8
RouteConstraint::Ulid ULID
RouteConstraint::Slug [A-Za-z0-9]+(?:-[A-Za-z0-9]+)*
RouteConstraint::Alpha [A-Za-z]+
RouteConstraint::AlphaNumeric [A-Za-z0-9]+

A request that does not satisfy the constraint does not match the route, so it falls through to the next route or to a 404:

Terminal window
$ curl http://127.0.0.1:3000/users/abc
{"type":"https:\/\/pam.dev\/problems\/4","title":"Route not found.","status":404,"code":4}

Give a route a name with name(). Names may contain letters, numbers, dots, dashes and underscores, and must be unique:

$router->get('/users/{id}', [UserController::class, 'show'])->name('users.show');

The name becomes the operationId of the route in the generated OpenAPI document.

Groups share a prefix, middleware and other attributes between routes. Each call returns a new registrar, so you can chain them and finish with group():

routes.php
use App\Middleware\EnsureApiKey;
use Nimbus\RouteRegistrar;
$router->prefix('api/admin')
->middleware(EnsureApiKey::class)
->group(function (RouteRegistrar $router): void {
$router->get('stats', fn () => ['users' => 42]); // GET /api/admin/stats
$router->get('health', fn () => ['ok' => true]); // GET /api/admin/health
});

Groups nest, and their prefixes and middleware accumulate:

$router->prefix('api')->group(function (RouteRegistrar $api): void {
$api->prefix('v1')->group(function (RouteRegistrar $v1): void {
$v1->get('status', fn () => ['version' => 1]); // GET /api/v1/status
});
});

The registrar offers these group attributes:

Method Effect on the routes of the group
prefix(string $prefix) Prepends a path prefix.
middleware($middleware) Adds middleware: an instance, a class name, a callable, a throttle: alias, or a list of them.
auth() Requires an authenticated principal.
can(string $ability, ?string $subject = null) Requires an ability; implies auth().
throttle(int $maxAttempts, int $decayMinutes = 1) Limits each client.
rateLimit(string $limiter) Applies a named rate limiter.
signed() Requires a valid signed URL.
controller(string $class, callable $routes) Lets routes name only the controller method.

When many routes use the same controller, controller() lets each route name only the method:

use App\Controllers\ProductController;
use Nimbus\RouteRegistrar;
$router->controller(ProductController::class, function (RouteRegistrar $router): void {
$router->get('api/products', 'index');
$router->post('api/products', 'store');
$router->get('api/products/{id}', 'show');
});

resource() registers the conventional routes of a controller in one call. The parameter name is the singular of the last path segment (products becomes {product}, categories becomes {category}):

$router->resource('products', ProductController::class);
Method Path Controller method
GET /products index
POST /products store
GET /products/{product} show
PUT /products/{product} update
PATCH /products/{product} update
DELETE /products/{product} destroy

Pass a closure to add more routes relative to the resource path, bound to the same controller:

$router->resource('users', UserController::class, function (RouteRegistrar $users): void {
$users->post('{user}/ban', 'ban'); // POST /users/{user}/ban
});

apiResource() registers the same six routes without the closure argument.

When a handler parameter is typed with a class and named like a route parameter, Nimbus turns the segment into an instance of that class. Implement Nimbus\Routing\RouteBindable on the class:

app/Models/Team.php
<?php
declare(strict_types=1);
namespace App\Models;
use Nimbus\Http\HttpException;
use Nimbus\Http\ProblemCode;
use Nimbus\Routing\RouteBindable;
final readonly class Team implements RouteBindable
{
public function __construct(public string $slug, public string $name)
{
}
public static function resolveRouteBinding(string $value): static
{
return match ($value) {
'acme' => new self('acme', 'Acme Corporation'),
default => throw new HttpException(404, ProblemCode::NotFound, 'Team not found.'),
};
}
}
routes.php
use App\Models\Team;
$router->get('/teams/{team}', fn (Team $team) => ['name' => $team->name]);
Terminal window
$ curl http://127.0.0.1:3000/teams/acme
{"name":"Acme Corporation"}
$ curl http://127.0.0.1:3000/teams/nope
{"type":"https:\/\/pam.dev\/problems\/4","title":"Team not found.","status":404,"code":4}

For classes you do not own, register a resolver on the container instead:

bootstrap/app.php
$app->container()->bindRoute(Invoice::class, function (string $value, Container $container): Invoice {
return $container->get(InvoiceRepository::class)->findOrFail((int) $value);
});

A typed value that a middleware put in the request context with RequestContext::put() wins over the route segment of the same name; see Middleware.

The router handles the methods you did not register in a predictable way:

  • Every GET route also answers HEAD. The body is removed after middleware runs, while the status and headers are kept.
  • A path that exists for other methods answers 405 Method Not Allowed with an Allow header.
  • An OPTIONS request to such a path answers 204 with the same Allow header.
  • An unknown path answers 404.

An explicit head() or options() route always wins.

Terminal window
$ curl -i -X DELETE http://127.0.0.1:3000/api/products
HTTP/1.1 405 Method Not Allowed
allow: GET, HEAD, OPTIONS, POST
content-type: application/problem+json; charset=utf-8
{"type":"https:\/\/pam.dev\/problems\/9","title":"Method Not Allowed","status":405,"code":9}

CORS preflight requests are answered by the PAM transport before routing; see CORS.

throttle() allows a number of requests per minute (or per several minutes) for each authenticated principal or client IP:

$router->post('/login', [LoginController::class, 'store'])->throttle(5); // 5 per minute
$router->post('/export', [ExportController::class, 'store'])->throttle(10, 60); // 10 per hour

Responses carry x-ratelimit-limit and x-ratelimit-remaining. Once the limit is reached the route answers 429 with retry-after and x-ratelimit-reset:

Terminal window
$ curl -i http://127.0.0.1:3000/limited # third request with throttle(2)
HTTP/1.1 429 Too Many Requests
retry-after: 60
x-ratelimit-remaining: 0
x-ratelimit-limit: 2

The Laravel-style string aliases work too: ->middleware('throttle:60,1').

Define reusable limiters on the application with rateLimiter()->for(). The callback receives the request and returns one Nimbus\RateLimit\Limit or a list of them:

bootstrap/app.php
use Nimbus\RateLimit\Limit;
use Pam\Http\Request;
$app->rateLimiter()->for('api', fn (Request $request) =>
Limit::perMinute(60)->by($request->getHeader('authorization') ?? 'guest')
);
routes.php
$router->prefix('api')->rateLimit('api')->group(function (RouteRegistrar $router): void {
$router->get('orders', [OrderController::class, 'index']);
});

Limit offers perSecond(), perMinute(), perMinutes(), perHour(), perDay() and none(), plus by() to choose the key and response() to replace the 429 body.

Routes can describe themselves for the generated OpenAPI 3 document:

$router->post('/products', [ProductController::class, 'store'])
->name('products.store')
->summary('Create a product')
->tags(['Products'])
->input(StoreProductRequest::class)
->output(ProductResource::class);

$app->docs() serves the document at /docs/openapi.json and an interactive reference page at /docs. Use $app->openApi('Acme API', '1.0.0')->toJson() to write the document during a build instead.

pam routes boots the application and prints every registered route as JSON, without serving traffic:

Terminal window
pam routes index.php
[
{
"kind": 4,
"method": "GET",
"path": "/api/ping"
},
{
"kind": 4,
"method": "GET",
"path": "/users/{id}"
}
]

Routing configuration is bounded so that a mistake cannot turn into an unbounded cost on every request:

  • 10,000 routes per application;
  • paths of up to 2 KiB, 128 segments and 32 parameters;
  • custom constraints of up to 512 bytes, compiled with PCRE match and depth budgets;
  • duplicate method and path pairs, or duplicate names, throw at registration time.

Routes can only be added while the application boots. Once the first request is handled the application is frozen, and registering a route throws a LogicException.