Skip to content

Routing

Routes map an HTTP method and path to a handler. You register them on Pam\App before the application starts. The router compiles every route once per worker and matches requests without re-reading your route files.

The simplest route takes a path and a closure. Closures receive the PAM request and response:

index.php
use Pam\App;
use Pam\Http\Request;
use Pam\Http\Response;
$app = new App();
$app->get('/greeting', static fn (Request $request, Response $response): Response =>
$response->json(['message' => 'Hello, Alice']));
$app->get($path, $handler);
$app->post($path, $handler);
$app->put($path, $handler);
$app->patch($path, $handler);
$app->delete($path, $handler);
$app->head($path, $handler);
$app->options($path, $handler);
$app->route('PURGE', $path, $handler); // any other valid method

Every method except route() returns a PendingRoute, which you use to add constraints, a name, middleware and OpenAPI metadata. route() returns the application.

A handler can be:

Handler Example Resolution
Closure or callable static fn (Request $r, Response $res) => ... Called with ($request, $response).
Invokable controller CreateOrderController::class Built by the container; __invoke() is called with injection.
Controller and method [UserController::class, 'show'] Built by the container; the method is called with injection.

Controller handlers are validated when you register the route: the class and a public, concrete method must exist. Dependency injection applies to controllers only; closures always receive the request and the response positionally. See Controllers & Container.

A handler may return:

  • a Pam\Http\Response (returned as is);
  • a Responsable, such as a JSON resource;
  • a string, integer, float or boolean, sent as text/plain when the response is still empty;
  • null, which keeps the response you were given.

Arrays are not converted automatically. Return $response->json($data) or a resource instead.

Wrap a segment in braces to capture it. Parameters are strings and are available through $request->route():

$app->get('/teams/{team}/members/{member}', static function (Request $request, Response $response): Response {
return $response->json([
'team' => $request->route('team'),
'member' => $request->route('member'),
]);
});

A parameter always occupies a whole segment, names must match [A-Za-z_][A-Za-z0-9_]* and must be unique within the route. Controller methods receive parameters by name; see Controllers & Container.

Constrain a parameter with where(). A request whose segment does not match falls through to 404:

use Pam\Api\RouteConstraint;
$app->get('/users/{id}', [UserController::class, 'show'])
->where('id', RouteConstraint::Integer);
$app->get('/invoices/{number}', [InvoiceController::class, 'show'])
->where('number', 'INV-[0-9]{6}');
Constraint Pattern
RouteConstraint::Integer [0-9]+
RouteConstraint::Uuid RFC 4122 UUID, versions 1 to 8
RouteConstraint::Ulid 26-character Crockford base32 ULID
RouteConstraint::Slug [A-Za-z0-9]+(?:-[A-Za-z0-9]+)*
RouteConstraint::Alpha [A-Za-z]+
RouteConstraint::AlphaNumeric [A-Za-z0-9]+

A custom constraint is a regular expression fragment of at most 512 bytes.

Give a route a unique name with name(). Names may contain letters, numbers, dots, dashes and underscores, and registering the same name twice throws. Names become the OpenAPI operationId:

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

prefix() returns a RouteRegistrar that shares a path prefix and middleware with every route defined in group():

routes.php
use Pam\Api\RouteRegistrar;
$app->prefix('/api/v1')
->middleware(Authenticate::class)
->group(function (RouteRegistrar $routes): void {
$routes->get('/me', [ProfileController::class, 'show']);
$routes->post('/orders', [OrderController::class, 'store']);
});

middleware() accepts one middleware or an array, and returns a new registrar, so you can derive several groups from a shared prefix. $app->group() without a prefix groups routes at the root. Registrars expose the same get, post, put, patch, delete, head and options methods as the application.

apiResource() registers the conventional JSON API actions for a controller:

$app->prefix('/api')->group(function (RouteRegistrar $routes): void {
$routes->apiResource('/photos', PhotoController::class);
});
Method Path Action
GET /api/photos index
POST /api/photos store
GET /api/photos/{photo} show
PUT /api/photos/{photo} update
PATCH /api/photos/{photo} update
DELETE /api/photos/{photo} destroy

The parameter name is the singular form of the last path segment. The controller must define all five methods, because each one is checked at registration.

When a controller parameter is typed with a class and named like a route parameter, the container converts the raw value. Implement RouteBindable on the class:

src/Models/Post.php
use Pam\Api\Http\HttpException;
use Pam\Api\Http\ProblemCode;
use Pam\Api\Routing\RouteBindable;
final class Post implements RouteBindable
{
public function __construct(public int $id, public string $title) {}
public static function resolveRouteBinding(string $value): static
{
return PostRepository::find((int) $value)
?? throw new HttpException(404, ProblemCode::NotFound, 'Post not found.');
}
}
src/Http/Controllers/PostController.php
final readonly class PostController
{
public function show(Post $post): PostResource
{
return new PostResource($post);
}
}

For classes you do not own, register a resolver on the container. It receives the raw value and the container:

$app->container()->bindRoute(Post::class, static fn (string $value, $container): Post =>
$container->get(PostRepository::class)->findOrFail((int) $value));

The resolver must return an instance of the typed class; anything else throws.

The router answers the routing edge cases for you:

  • HEAD matches every GET route. The body is removed after middleware and error handling, while status and headers are kept. An explicit head() route wins.
  • OPTIONS returns 204 with an Allow header listing the methods of the path when no explicit options() route exists.
  • Unknown path returns a 404 Problem Details response (code 4).
  • Known path, wrong method returns 405 with an Allow header and code 9.
  • Duplicate method and path throws while you register routes.
Terminal window
curl -i -X DELETE http://127.0.0.1:3000/api/ping
# HTTP/1.1 405 Method Not Allowed
# content-type: application/problem+json; charset=utf-8
# allow: GET, HEAD, OPTIONS
#
# {"type":"https://pam.dev/problems/9","title":"Method Not Allowed","status":405,"code":9}

Route paths must be absolute and cannot contain a query string. Static paths are normalized for a trailing slash. The router enforces explicit limits so a misconfiguration cannot grow without bound: 10,000 routes per application, paths up to 2 KiB, 128 segments and 32 parameters per route. Compiled patterns carry PCRE match and depth budgets, and oversized request paths are rejected before any regular expression runs.

pam routes loads your entry file and prints the registered routes as JSON without starting the server:

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