PHP Luminova: HTTP Request Routing
Explore Luminova HTTP Routing for web and API applications, with clean controller-based routes, HTTP methods, route attributes, middleware, dependency injection, and response caching.
The HTTP Routing documentation covers routing for HTTP controllers, including both web and API requests handing.
Routes map controller methods or closure handler to HTTP methods such as GET, POST, PUT, DELETE, and QUERY. This keeps route definitions explicit, predictable, and easy to maintain.
To get started, see the Luminova Routing System Introduction for an overview of the routing system, configuration, and features shared between HTTP and CLI routing.
Response Content Caching
Luminova supports template content caching to improve response performance and reduce server load. Cached content can be served directly instead of regenerating the template for every request.
Luminova also supports version-based caching, which is useful for documentation, versioned applications, and other sites where different application versions need separate cached content.
For example:
https://example.com/1.1.0/aboutThe /1.1.0/ version prefix allows the corresponding content to be cached and served independently from other application versions, when available.
For information about enabling and configuring view caching, see the View Caching Guide.
Usages
Controller Method-Based Handlers
Route handlers can be defined using a Closure or a string reference to a controller method.
Luminova supports two controller method reference formats:
- Static-style:
Controller::method - Notation-style:
Controller@method
The controller name does not need to include its full namespace. Luminova resolves the controller from the registered controller list.
Note:
Within a /routes/<uri-prefix>.php file, the following objects are automatically available:
Luminova\Routing\Router $routerApp\Application $app
You do not need to import these classes unless you need to reference them explicitly, such as when using bind() with dependency injection.
Static-style Reference
// /routes/web.php
Router::get('/', 'HomeController::index');Notation-style Reference
// /routes/web.php
Router::get('/', 'HomeController@index');Both references resolve to the index() method of App\Controller\Http\HomeController.
Closure Handler
A route can also use a Closure as its handler:
// /routes/web.php
use function Luminova\Funcs\view;
Router::get('/', function (): int {
return view('index')->render([
'title' => 'Welcome',
]);
});Closures can also use dependency injection. Non-builtin typed parameters are automatically resolved and injected when route dependency injection is enabled.
Grouping Routes with
The bind method groups routes under a common URI prefix or pattern.
It accepts two arguments:
- A URI prefix or group pattern.
- A Closure containing the routes to register.
The prefix is automatically prepended to each route defined inside the Closure. Non-builtin typed parameters declared by the Closure are automatically resolved and injected.
// /routes/web.php
Router::get('/', 'MainController::index');
Router::bind('/about/(:root)', function (): void {
Router::get('/', 'MainController::about');
Router::get('/team', 'MainController::team');
});The routes above produce the following URI structure:
/
├── /about/
└── /about/teamThis keeps related routes together without repeating the common /about prefix.
See Dynamic Segment Capturing for more information about route placeholders.
Handling Any HTTP Method
The any method registers a route that accepts requests using any HTTP method, including GET, POST, PUT, PATCH, DELETE, and other supported HTTP methods.
This is useful when the same handler should process a request regardless of its HTTP method, such as a general-purpose endpoint or a route used for testing and debugging.
Examples:
Using the any method:
// /routes/web.php
use Luminova\Routing\Router;
Router::any('/action', 'ExampleController::action');Using capture with Router::ANY_METHOD:
// /routes/web.php
use Luminova\Routing\Router;
Router::capture(
Router::ANY_METHOD,
'/action',
'ExampleController::action'
);Both routes accept requests using any HTTP method.
You can also define an any-method route using the controller method-level Route attribute:
// /app/Controllers/Http/ExampleController.php
use Luminova\Attributes\Route;
#[Route('/action', methods: ['ANY'])]
public function action(): int
{
// Handler implementation.
return STATUS_SUCCESS;
}Capturing Selected HTTP Methods
Use capture when a single route should accept only a specific set of HTTP methods.
// /routes/web.php
use Luminova\Routing\Router;
Router::capture(
'POST|GET|PUT',
'/action',
'ExampleController::action'
);The same route can be defined using the Route attribute:
// /app/Controllers/Http/ExampleController.php
use Luminova\Attributes\Route;
#[Route('/action', methods: ['POST', 'GET', 'PUT'])]
public function action(): int
{
// Handler implementation.
return STATUS_SUCCESS;
}In this example, the route accepts only POST, GET, and PUT requests. Other HTTP methods are not matched by the route.
Note:
Router::ANY_METHODrepresents all HTTP methods and cannot be combined with individual HTTP methods.
Dependency Injection
Luminova routing can automatically resolve and inject dependencies into controller methods and route callbacks.
To use dependency injection, type-hint the class you need in the method or callback signature. Luminova resolves the dependency and passes the instance to the handler automatically.
Luminova also supports resolving union types and intersection types when their dependencies can be resolved.
Examples:
Using a controller method:
// /app/Controllers/Http/UserController.php
namespace App\Controllers\Http;
use Luminova\Base\Controller;
use Luminova\Http\Request;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
#[Prefix('/user/(:base)')]
class UserController extends Controller
{
#[Route('/user/(:username)', methods: ['GET'])]
public function user(string $username, Request $request): int
{
$name = $request->getGet('name');
// Your logic here.
return STATUS_SUCCESS;
}
}Using a route callback:
// /routes/web.php
use Luminova\Http\Request;
Router::get('/user/(:username)', function (
string $username,
Request $request
): int {
$name = $request->getGet('name');
// Your logic here.
return STATUS_SUCCESS;
});In both examples, $username is populated from the matched URI segment, while the Request object is resolved and injected automatically.
This allows handlers to declare the dependencies they need without manually creating or retrieving framework services.
For more details, see the Dependency Injection documentation.
Note:
If
env(feature.route.dependency.injection)is disabled, dependency injection is not performed. Only values captured from the matched URI segments are passed to the route handler.Enable route dependency injection to allow class type-hints to be automatically resolved and injected.
Attributes
Method-level Route Attribute
A method-scope, repeatable attribute used to register an HTTP route on a controller method.
Example:
#[Route('/(:root)', methods: ['ANY'], middleware: Route::BEFORE_MIDDLEWARE)]
public function middleware(): int
{
// Middleware implementation.
return STATUS_SUCCESS;
}
#[Route('/', methods: ['GET'])]
public function index(): int
{
// Method implementation.
return STATUS_SUCCESS;
}
#[Route('/user/(:username)', methods: ['GET'])]
public function user(string $username, Request $request): int
{
// Method implementation.
return STATUS_SUCCESS;
}For more details, see the Route Attribute documentation.
Class-level Prefix Attribute
A class-scope attribute that assigns a URI prefix and, optionally, an exclusions and error handler to an HTTP controller.
A controller can have only one Prefix attribute.
The prefix determines the URI space handled by the controller, including requests that do not match a specific route, unless the paths are explicitly excluded.
Example:
Define a custom URI prefix:
namespace App\Controllers\Http;
use Luminova\Base\Controller;
use Luminova\Attributes\Prefix;
#[Prefix('/blog/(:base)')]
class BlogController extends Controller {}Define endpoint exclusions:
namespace App\Controllers\Http;
use Luminova\Base\Controller;
use Luminova\Attributes\Prefix;
#[Prefix('/(:base)', exclude: ['api', 'blog', 'admin'])]
class MainController extends Controller {}The exclude option prevents the specified URI segments from being handled by the controller.
Equivalent raw pattern:
#[Prefix(
pattern: '/(:base)(?!api(?:/|$)|blog(?:/|$)|admin(?:/|$)).*'
)]
class MainController extends Controller {}Both examples configure the main controller to handle requests under the root URI while excluding /api, /blog, and /admin.
Using a Prefix attribute on the main entry controller provides a centralized way to define the application's default URI scope and its exclusions.
It is recommended to define application-level URI exclusions on the main entry controller using the
Luminova\Attributes\Prefixclass-scope attribute.
For more details, see the Prefix Attribute documentation.
For dynamic placeholder syntax such as (:base), (:root), and (:int), see Dynamic Segment Capturing.
Class-level Error Attribute
A class-scope, repeatable attribute used to register an HTTP error handler for a specific URI pattern within a routing context.
Example:
namespace App\Controllers\Http;
use Luminova\Base\Controller;
use Luminova\Attributes\Error;
use App\Errors\Controllers\AppError;
// Global website error handler.
#[Error(pattern: '/', onError: [AppError::class, 'onWebError'])]
// Custom error handler for the `/foo/` URI prefix.
#[Error(
'dashboard',
pattern: '/foo/',
onError: [AppError::class, 'onDashboardError']
)]
class GlobalController extends Controller
{
// Controller implementation.
}Multiple Error attributes may be defined on the same controller, allowing different error handlers to be associated with different URI patterns.
For more details, see the Error Attribute documentation.
Class Definition
- Class namespace:
Luminova\Routing\Router - This class implements: \Luminova\Interface\RouterInterface
- This class is marked as final and can't be subclassed
Constants
| Constant | Value | Description |
|---|---|---|
Router::ANY_METHOD | ANY | Accept any incoming HTTP request method. |
Methods
get
Get, a shorthand for the capture method to handle the GET request method.
public static get(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
query
Query, a shorthand for the capture method to handle the QUERY request method.
public static query(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /search, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
post
Post, a shorthand for the capture method to handle the POST request method.
public static post(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
patch
Patch, a shorthand for the capture method to handle the PATCH request method.
public static patch(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
delete
Delete, a shorthand for the capture method to handle the DELETE request method.
public static delete(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
put
Put, a shorthand for the capture method to handle the PUT request method.
public static put(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
options
Options, a shorthand for the capture method to handle the OPTIONS request method.
public static options(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback to execute (e.g., ClassBaseName::methodName). |
middleware
Registers an HTTP before middleware to authenticate requests before handling controllers.
This method allows you to apply middleware security logic that executes prior to any associated HTTP controllers. If the middleware callback returns STATUS_ERROR (or STATUS_SILENCE), routing terminates and onMiddlewareFailure() is invoked on the controller.
Middlewares can be registered within a bind() closure for a specific URI prefix, or in the global scope of the routing context. It also supports regular expression patterns and pipe-separated methods to match before executing.
public static middleware(string $methods, string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$methods | string | The allowed HTTP methods, separated by a | pipe symbol (e.g., GET|POST). |
$pattern | string | The route URL pattern or template name (e.g., /.*, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback function or controller method to execute. |
Throws:
- \Luminova\Exceptions\RouterException - Thrown if called in a non-HTTP context, or if
$methodsis empty.
after
Registers an HTTP after middleware to execute logic after a controller has been handled.
This method applies middleware logic that runs after a controller processes a request. It is typically used for tasks such as cleanup or additional post-processing.
public static after(string $methods, string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$methods | string | The allowed HTTP methods, separated by a | pipe symbol (e.g., GET|POST). |
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9])). |
$callback | Closure|string | The callback function or controller method to execute (e.g., ClassBaseName::afterMethodName). |
Throws:
- \Luminova\Exceptions\RouterException - Thrown if the
$methodsparameter is empty.
Note: This method can only be used with
HTTPrequest routing; it is not allowed inCLImode.
capture
Registers HTTP request methods, URI patterns, and corresponding callback or controller methods.
This method allows you to define routes by specifying supported HTTP methods, a URL pattern, and the callback or controller method to execute when the pattern matches a client request. Multiple HTTP methods can be specified using the pipe (|) symbol.
public static capture(string $methods, string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$methods | string | The allowed method(s); multiple HTTP methods can be separated by a | pipe symbol (e.g., GET\|POST\|PUT or ANY). |
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9]) or /user/(:placeholder)). |
$callback | Closure|string | The callback function or controller method to execute (e.g., ClassBaseName::methodName). |
Throws:
- \Luminova\Exceptions\RouterException - Thrown if an empty method string is provided.
any
Capture and handle requests for any HTTP method.
This method leverages Router::ANY_METHOD to match and handle requests for any HTTP method. It is a convenient way to define routes that respond to all HTTP methods without explicitly specifying them.
public static any(string $pattern, Closure|string $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$pattern | string | The route URL pattern or template name (e.g., /, /home, /user/([0-9])). |
$callback | Closure|string | The callback function or controller method to execute (e.g., ClassBaseName::methodName). |
bind
Groups related HTTP routes under a common URI prefix.
The bind method prepends the specified prefix to every route defined within the callback. This allows related routes to be organized under a shared URI structure and supports nested route groups.
Non-builtin typed parameters declared by the callback are automatically resolved and injected through dependency injection.
Middleware may also be applied within the callback, allowing middleware to be scoped to the routes defined by the group.
public static bind(string $prefix, Closure $callback): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$prefix | string | The URI prefix or pattern to prepend to routes in the group, such as /blog, /account/([a-z]), or /account/(:placeholder). |
$callback | Closure(T ...$di): void | A closure containing the routes to register under the specified prefix. Typed parameters that are not built-in types are automatically resolved and injected. |
Example:
Router::bind('/blog/', static function (): void {
Router::middleware('GET', '/(:root)', 'Authentication::isAllowed');
Router::get('/', 'BlogController::all');
Router::get('/([a-zA-Z0-9-]+)', 'BlogController::read');
Router::patch('/update/([a-zA-Z0-9-]+)', 'BlogController::update');
});The routes above are registered under the /blog prefix:
| Route | Controller action |
|---|---|
/blog/ | BlogController::all() |
/blog/{slug} | BlogController::read() |
/blog/update/{slug} | BlogController::update() |
Using bind keeps related routes together and makes shared URI prefixes easier to maintain.
onError
Registers a custom error handler globally or for a specific URI pattern.
The handler is registered globally by default. To associate the handler with a specific URI pattern, pass the pattern as the second argument.
An error handler may be a closure, a controller callback, or a callable class name. The router can resolve dependencies and matched URI segments according to the handler's parameters.
public static function onError(
Closure|array $handler,
string $pattern = '/'
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | (Closure(mixed ...$di):int)\|array{0:class-string,1:string} | Error handler to execute. Accepts a closure, callable class name, or controller callback such as [ControllerClass::class, 'method']. |
$pattern | string | URI pattern associated with the handler. Defaults to /, which registers the handler globally. |
Throws:
- \Luminova\Exceptions\RouterException - Thrown if
$handleris not a valid callable.
Controller Attributes
Class-level prefix attribute:
An error handler can be registered directly on a controller using the Prefix attribute. The handler applies to errors matching the controller's URI prefix.
use Luminova\Attributes\Prefix;
#[Prefix(
pattern: '/users/(:base)',
onError: [AppError::class, 'onTrigger']
)]
class UserController extends Controller
{
// ...
}class-level error attribute:
use Luminova\Attributes\Error;
#[Error(
pattern: '/users/(:base)',
onError: [AppError::class, 'onTrigger']
)]
class UserController extends Controller
{
// ...
}Global error handler:
Register a handler globally by omitting $pattern:
Router::onError([AppError::class, 'onTrigger']);URI-specific error handler:
Register a handler for a specific URI pattern:
Router::onError(
[AppError::class, 'onTrigger'],
'/users'
);The pattern may contain route parameters supported by the router:
Router::onError(
[AppError::class, 'onTrigger'],
'/users/(:base)'
);Using a closure:
Router::onError(
function (int $status, Segments $segments): int {
// Handle the error.
return STATUS_SUCCESS;
},
'/admin'
);Method-based Route Definition
Method-based prefix error handlers:
Error handlers can also be associated with a router context prefix using Prefix::with():
Boot::http()->router->context([
Prefix::with(
Prefix::WEB,
[AppError::class, 'onTrigger']
),
Prefix::with(
Prefix::API,
[AppError::class, 'onApiErrorTrigger']
),
Prefix::with(
'test',
function (Segments&Stringable $segments, int $status) {
// Handle errors for the "test" prefix.
}
),
])->run();A prefix handler can use dependency injection and type declarations, including intersection types:
Manually triggering an error:
After an error handler is registered, an HTTP error can be triggered explicitly:
$this->app->router::trigger(500);
// Or
Router::trigger(500);The router selects the applicable handler based on the registered URI pattern or prefix context.
trigger
Trigger an HTTP error response and immediately halt route processing.
This method is called when no matching route is found, or when a request must return a specific HTTP status code (e.g., 404, 500). It delegates error handling in the following order:
- If
AppError::onTrigger()exists, it is called directly. - If a matching route-specific error handler is registered (via
onError()), that handler is executed. - If a global (
'/') error handler is registered, that handler is executed. - If no handler is found, a default error page is displayed.
public static trigger(int $status = 404): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP status code to trigger (default: 404). |
This method can be used anywhere in a controller class as
$this->app->router::trigger(), or in a routing context asRouter::trigger();.This method clears output buffers to ensure no partial output is sent before the error response is generated. Once an error response is sent, execution stops immediately.
getUriPath
Get the current request URI path.
The path is normalized with a leading / and without a trailing /. The query string is excluded. The resolved value is cached for the remainder of the request.
public static getUriPath(): stringReturn Value:
string - The normalized URI path.
Example:
https://example.com/products/view/10 → /products/view/10
https://example.com/products/view/10?foo=bar → /products/view/10
https://example.com → /getUriSegments
Get the URI segments as an array.
Splits the current request URI path into individual segments and removes the public prefix when it appears as the first segment.
public static getUriSegments(): arrayReturn Value:
array<int,string> - The URI segments.
Example:
/public/foo/bar → ['foo', 'bar']
/public → []
/products/view/10 → ['products', 'view', '10']
/ → []See Also: getSegment
getSegment
Get the current request URI segments as a Segments object (see URI Segment Object).
public static getSegment(): SegmentsReturn Value:
Segments - The URI segments for the current request.
Example:
$segments = Router::getSegment();
echo $segments->position(0);
echo $segments->toString();isSegment
Determine whether current request URI segment matches the given name.
public static isSegment(string $name, int $position = 0): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The URI segment name to match. |
$position | int | The zero-based segment position (default: 0). |
Return Value:
bool - true if the segment at the given position matches the name.
Examples:
// Prefix
if (Router::isSegment('admin')) {
// Matches: /admin or /admin/users
}
// Position
if (Router::isSegment('users', 1)) {
// Matches: /admin/users or /api/users
}isUriPrefix
Determine whether the first URI segment matches any given prefix.
public static isUriPrefix(array|string $prefix): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$prefix | array|string | One or more URI prefixes to match. |
Return Value:
bool - true if the first URI segment matches any given prefix.
Examples:
// Single prefix
if (Router::isUriPrefix('admin')) {
// Matches: /admin or /admin/users
}
// Multiple prefixes
if (Router::isUriPrefix(['api', 'webhook'])) {
// Matches: /api/* or /webhook/*
}isApiPrefix
Determine whether the current request uses the configured API URI prefix.
The request matches when its first URI segment equals the configured API prefix, such as /api or a custom prefix defined by app.api.prefix.
public static isApiPrefix(): boolReturn Value:
bool - true if the first URI segment matches the configured API prefix.
isApiRequest
Determine whether the current request should be treated as an API request.
A request is considered an API request when its first URI segment matches the configured API prefix name, or when AJAX requests are configured to qualify as API requests.
public static isApiRequest(?bool $ajaxAsApi = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$ajaxAsApi | bool|null | Whether to treat AJAX requests as API requests. When null, the value is resolved from app.validate.ajax.asapi. |
Return Value:
bool - true if the request matches the API prefix or qualifies as AJAX.