PHP Luminova: Application Routing System
The Luminova routing system handles incoming HTTP requests and routable CLI controller commands. It resolves each request and invokes the appropriate controller to handle it.
The Routing System is a core component of the Luminova Framework. It matches incoming requests to the appropriate controller and handler, then dispatches them to produce the intended response. It also supports static cache delivery and request-level middleware, allowing tasks such as authentication and authorization to run before a request reaches the controller.
The router supports both:
- HTTP controllers — see Base Controller Classes
- CLI command controllers — see Base Command Classes
The routing system loads only the relevant routes and controllers for the current request based on its URI prefix or CLI command group. It then resolves the matching handler and applies any configured middleware before dispatching the request.
Luminova provides several optional routing features that can be enabled or disabled through the Environment Configuration (
.env) file according to your application's requirements.
Route Definition Methods
Luminova supports both PHP Attribute and method-based route definitions, allowing you to choose the coding style that best fits your application.
Note:
Attribute routing and method-based routing cannot be used together. To use attribute routing, enable it in
.envfile withfeature.route.attributes. To use method-based routing, you must disable attribute routing.
Attribute Routing
Disabling Attribute Routing
Attribute routing is enabled by default.
If you prefer to define routes manually using routing methods, disable attribute routing:
feature.route.attributes = trueRoute Attribute Classes
Luminova provides PHP attribute classes for defining HTTP routes, CLI commands, and related routing configuration directly in your controllers. This keeps route definitions close to the code that handles them and makes applications easier to maintain than method-based routing.
HTTP Attributes
Luminova\Attributes\Route— Defines individual HTTP routes and their supported methods. See HTTP Routing.Luminova\Attributes\Prefix— Defines a common URI prefix for an HTTP controller class. See HTTP Routing.Luminova\Attributes\Error— Defines HTTP error handlers for a controller class. See HTTP Routing.
CLI Attributes
Luminova\Attributes\Group— Defines a command group for a CLI controller class. See CLI Routing.Luminova\Attributes\Command— Defines individual CLI command routes. See CLI Routing.
Attribute Optimization
Attribute routing includes optional optimizations for route resolution and production caching. These reduce the need to scan and parse route attributes on every request.
Caching Route Attributes
For better production performance, you can cache route attributes to prevent them from being parsed on every request:
feature.route.cache.attributes = trueNote:
When attribute caching is enabled, new or modified routes will not take effect until the route cache is cleared.
To apply route changes, manually remove the cached files from:
/writeable/caches/routes/*or from the corresponding prefix directory, if applicable.
Optimizing Attribute Routes
When enabled, route attributes are scored and sorted to improve route resolution performance:
route.optimize.attributes = trueThis optimization runs only once when
feature.route.cache.attributesis enabled.
Method-Based Routing
Method-based routing is the traditional way to define routes using HTTP method verbs and other methods provided by the routing system. It is a simple approach that works well for smaller applications or applications that prefer centralized route definitions.
Route Handler Definitions
Route handlers can be defined using either a closure or a controller method reference.
Luminova supports two controller method reference formats:
- Static-style:
ControllerName::method - Annotation-style:
ControllerName@method
The controller's full namespace is not required. You can specify the controller's base name and method, and the routing system will resolve the controller from the registered controller namespaces. See addNamespace.
Examples:
// /routes/web.php
Router::get('/', 'MainController::index');
Router::get('/', function (): int {
// Handle request
});Method-Based Route Prefixing
The Luminova\Routing\Prefix class defines routing contexts for HTTP and CLI requests. A prefix can optionally specify an error handler and allows routes to be organized into separate route files.
Instead of placing all routes in default routes/web.php, you can create a dedicated route file for a custom prefix, such as routes/user.php.
For more information, see Method-Based URI Routing Prefixing.
Route Prefix Grouping
Route prefix groups allow the routing system to load only the route file associated with the current request context instead of loading all routes from a single routes/web.php file. This reduces route loading overhead and can improve routing performance.
Example:
// /public/index.php
declare(strict_types=1);
use Luminova\Boot;
use Luminova\Routing\Prefix;
use App\Errors\Controllers\AppError;
// Autoload system boot
require_once __DIR__ . '/../system/Boot.php';
/**
* Set the application document root as the current working directory.
*/
if (getcwd() . DIRECTORY_SEPARATOR !== DOCUMENT_ROOT) {
chdir(DOCUMENT_ROOT);
}
/**
* Define routing contexts.
*/
Boot::http()->router->context([
Prefix::with(Prefix::CLI), // Default CLI routes
Prefix::with(Prefix::WEB, [AppError::class, 'onTrigger']), // Default web routes
Prefix::with(Prefix::API, [AppError::class, 'onTrigger']), // Default API routes
Prefix::with('user', [AppError::class, 'onTrigger']), // Custom user routes
])->run();For the custom user prefix, create a corresponding route file in /routes/ and define all user related routes.
// /routes/user.php
Router::middleware('ALL', '/user/(:base)', 'UserController::authenticate');
Router::get('/user', 'UserController::all');
Router::put('/user', 'UserController::create');
Router::get('/user/(:username)', 'UserController::find');
Router::patch('/user/(:username)', 'UserController::update');
Router::delete('/user/(:username)', 'UserController::delete');This ensures that requests with the
userprefix, such ashttps://example.com/user/peter, are resolved usingroutes/user.php, reducing route scanning overhead and improving response time.
Handler Return Types
Luminova routing handlers support different return types depending on whether the route is HTTP or CLI:
- HTTP handlers can return an integer status code or a supported response object.
- CLI handlers must return an integer status code.
This applies to both controller methods and closure handlers.
HTTP Response Objects
HTTP handlers can return any object that implements either Luminova\Interface\ContentResponseInterface or Psr\Http\Message\ResponseInterface.
Response objects are useful when you need direct control over the HTTP response, such as returning HTML, JSON, files, or responses for JavaScript frameworks such as React, Vue, Next.js, or Nuxt.
Example:
// /app/Controllers/Http/*
use Luminova\Attributes\Route;
use Luminova\Template\Response;
#[Route('/')]
public function index(): Response
{
return new Response(
content: '<h1>Hello World!</h1>',
status: 200
);
}Note:
Response objects are supported only by HTTP controller methods and closure handlers. CLI command handlers must return an integer status code.
HTTP Response Classes
The following built-in response classes are available:
Luminova\Http\Message\Response— PSR-7 HTTP response implementation that implementsPsr\Http\Message\ResponseInterface.Luminova\Template\Response— Template response implementation that implementsLuminova\Interface\ContentResponseInterface.
Integer Status Codes
Integer status codes provide the simplest way to return a result from a routing handler. They are commonly used with the Template View Class, whose rendering methods return an int, and are required for CLI command handlers.
Luminova provides special status constants to indicate whether a handler or middleware completed successfully, failed, or handled the response internally.
HTTP Handlers
STATUS_SUCCESS- Regular handler: The request was handled successfully.
- Middleware: The middleware check passed and routing continues.
STATUS_ERROR- Regular handler: The request failed and the routing system triggers an error response.
- Middleware: The middleware check failed, routing stops, and
Controller::onMiddlewareFailure()is invoked.
STATUS_SILENCE- Regular handler: The request was handled internally, such as when a custom error response has already been displayed.
- Middleware: Behaves like
STATUS_ERROR, but skipsController::onMiddlewareFailure()and stops routing. UseSTATUS_SUCCESSorSTATUS_ERRORfor middleware whenever possible.
CLI Handlers
CLI controller methods and closure handlers must return an int exit code.
STATUS_SUCCESS— The command or middleware check completed successfully.STATUS_ERROR— The command failed or a middleware check rejected execution.
Note:
If you need to stop request processing without returning a status code to the routing system, you can use other termination mechanisms, such as throwing
Luminova\Exceptions\HttpException, callingLuminova\Luminova::terminate(), or usingexit.
Routing Dependency Injection
Luminova provides dependency injection for routable controller methods and closure handlers through the Luminova\Routing\DI dependency resolver.
When enabled, the router automatically resolves non-builtin, type-hinted parameters and injects the corresponding dependencies into the handler. You can also register custom bindings to control which instance is provided for a class or interface.
Enabling Routing Dependency Injection
Routing dependency injection allows dependencies to be automatically injected into:
- Routable controller methods.
- Route closure handlers.
Router::bind()andRouter::group()closure handlers.- Error handler closures
Router::onError(). - Error controller classes that implement
Luminova\Interface\ErrorControllerInterface.
Dependency injection is disabled by default. To enable it, add the following setting to your environment configuration:
feature.route.dependency.injection = enableSee the Dependency Injection documentation for detailed examples and supported dependency types.
Registering Dependencies
You can register custom dependency bindings using DI::bind() or the controller's bind() method.
Bindings can be registered from:
- A controller's
onCreate()method. - The application's
onPreCreate()oronCreate()method. /app/Utils/Global.phpwhenfeature.app.dev.functionsis enabled.
A binding defines how the router should create or resolve a dependency when the corresponding class or interface is type-hinted.
Application binding:
// /app/Application.php
use App\Models\User;
use App\Service\UserService;
protected function onCreate(): void
{
$this->bind(UserService::class, function (): User {
return new UserService(
user: new User(attributes: [
'id' => 100,
'age' => 30,
'name' => 'Peter',
])
);
});
}Controller binding:
// /app/Controllers/Http/UserController.php
use App\Models\User;
use App\Service\UserService;
use Luminova\Routing\DI;
protected function onCreate(): void
{
DI::bind(UserService::class, function (): User {
return new UserService(
user: new User(attributes: [
'id' => 100,
'age' => 30,
'name' => 'Peter',
])
);
});
}Once registered, the router can resolve UserService automatically when it is type-hinted by a routable handler.
Injecting Dependencies
Once routing dependency injection is enabled, you can type-hint dependencies directly in controller methods and route closure handlers. The router resolves registered dependencies and injects them alongside captured route parameters.
Controller method:
// /app/Controllers/Http/UserController.php
use App\Service\UserService;
use Luminova\Attributes\Route;
#[Route('/user/(:int)')]
public function profile(int $userId, UserService $user): int
{
echo $userId;
echo $user->name;
return STATUS_SUCCESS;
}Route closure:
// /routes/user.php
use App\Service\UserService;
Router::get(function (int $userId, UserService $user): int {
echo $userId;
echo $user->name;
return STATUS_SUCCESS;
});Captured route parameters and injected dependencies can be used together. In this example, $userId is resolved from the (:int) route placeholder, while $user is resolved through dependency injection.
Intersection Type Dependencies
You can also use PHP intersection types when a handler requires a dependency that satisfies multiple interfaces.
An intersection type uses the & operator:
public function log(
LoggerInterface&FormatterInterface $service
): int {
// Handle request
}The injected object must implement all interfaces specified by the intersection type.
Example:
interface LoggerInterface
{
public function log(string $message): void;
}
interface FormatterInterface
{
public function format(string $message): string;
}
class Logger implements LoggerInterface, FormatterInterface
{
public function log(string $message): void
{
// Log message
}
public function format(string $message): string
{
return strtoupper($message);
}
}Register the implementation with the dependency resolver:
use Luminova\Routing\DI;
DI::bind(
LoggerInterface::class,
fn(): Logger => new Logger()
);The same resolved instance can then be injected into a handler requiring both interfaces:
#[Route('/log')]
public function log(
LoggerInterface&FormatterInterface $service
): int {
$service->log(
$service->format('Hello World')
);
return STATUS_SUCCESS;
}Because Logger implements both LoggerInterface and FormatterInterface, it satisfies the intersection type and can be injected by the router.
Dynamic URI Segment Capturing
URI segment capturing allows you to extract values from the request URI or CLI command string and pass them as arguments to controller methods or closure handlers.
Captured parameters can be combined with dependency injection, allowing additional dependencies to be automatically injected into the handler.
#[Route('/user/(:username)')]
public function user(string $username, Request $request): int
{
// Handle request
}
// Using a closure handler
Router::get(function (string $username, Request $request): int {
// Handle request
});There are several ways to define capture patterns:
Predefined Pattern Placeholders (Recommended)
Built-in placeholders provide predefined matching rules and type validation, making route definitions simpler and safer.
/view/(:string)/(:int)Typed placeholders can be made optional by prefixing the type with ?, for example (:?int), (:?string), or (:?numeric).
Regular Expressions (Advanced)
Regular expressions provide full control over the values a route can match, but require more complex patterns.
/view/([a-zA-Z0-9]+)/([0-9]+)Named Placeholders (Basic)
Named placeholders provide a simple and readable way to capture URI segments, but offer less control over value validation.
/view/{title}/{id}Registering a Custom Placeholder
You can register reusable regular expression patterns as custom placeholders. Custom placeholders work like predefined placeholders, allowing you to keep route definitions clean and maintainable.
// /app/Application.php
protected function onPreCreate(): void
{
Router::pattern('slug', '[a-z0-9-]+');
}Once registered, the custom placeholder can be used in route definitions like a built-in placeholder:
#[Route('/post/(:slug)')]Note:
Register custom patterns in the application class's
onPreCreate()oronCreate()method. This ensures the patterns are registered before the routing system begins processing requests.
URI Segment Object
The Luminova\Routing\Segments class provides access to the current request's URI segments. In CLI mode, it contains a single synthetic segment. The object is returned by Router::getSegment().
Example:
$segments = Router::getSegment();
echo $segments->position(0);
echo $segments->toString();For more information, see the Request URI Segments documentation.
Routing Class Definition
- Class namespace:
Luminova\Routing\Router - This class implements: \Luminova\Interface\RouterInterface
- This class is marked as final and can't be subclassed
Methods
The methods below are shared between HTTP and CLI routing. For method-specific APIs (route registration shorthands, middleware, commands), see HTTP Routing and CLI Routing.
__construct
Initializes the router. When $app is omitted, the shared application instance is resolved from the framework kernel.
public __construct(?Luminova\Foundation\Core\Application $app = null)setApplication
Assign the application instance used by the router.
public setApplication(Application $app): selfaddNamespace
Registers an MVC or HMVC controller namespace group for application routing.
This method allows the registration of new routable namespaces, making controllers within those namespaces accessible for routing in both HMVC and MVC applications.
Namespace Pattern:
Register your namespace up to the controller path, excluding the Http and Cli suffixes.
- HMVC Example: Use
App\Modules\Blog\Controllers\instead ofApp\Modules\Blog\Controllers\Http.This allows the routing system to capture and resolve bothHttpandClinamespaces under the registered group.
public addNamespace(string $namespace): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$namespace | string | The namespace to register (e.g., App\Controllers\, App\Modules\Blog\Controllers\). |
Return Value:
self - Returns the instance of the router class.
Throws:
- \Luminova\Exceptions\RouterException - If the namespace is empty or does not resolve to a valid MVC/HMVC controllers namespace.
Example:
Registering namespaces for HMVC module controllers, typically inside your application's onCreate():
// /app/Application.php
namespace App;
use Luminova\Foundation\Core\Application as CoreApplication;
class Application extends CoreApplication
{
protected function onCreate(): void
{
// Register HMVC module namespaces
$this->router->addNamespace('\\App\\Modules\\Admins\\Controllers\\');
$this->router->addNamespace('\\App\\Modules\\Users\\Controllers\\');
}
}Note:
For MVC and HMVC applications, the default root controllers namespace are already defined in the
Luminova\Foundation\Core\Applicationclass.UseaddNamespaceonly to extend routing for additional custom HMVC module controllers.
getNamespaces
Get the registered controller namespaces.
public static getNamespaces(): arrayReturn Value:
array<int,string> - The registered controller namespaces.
context
Registers the application routing context based on URI prefixes (e.g., web, cli, api, console) or custom prefix names.
The context method is an essential part of Luminova's routing optimization strategy. It initializes and loads routes based on a given URI prefix, allowing the framework to load only the relevant route files (like routes/web.php, routes/api.php, or routes/cli.php) at runtime. This method improves performance by avoiding loading all routes at once.
If no specific prefix is matched, the default web context handles the request.
The context method also supports defining custom error handlers for each prefix, similar to using attribute-based routing. It accepts either an array of Luminova\Routing\Prefix objects, an array of context definition arrays (as returned by Prefix::with()), or null when using PHP attributes.
public context(?array $contexts = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$contexts | Prefix[]|array<string|int,array>|null | Routing context definitions, or null to use attribute-based routing. |
Return Value
self - Return router instance class.
Throws:
- \Luminova\Exceptions\RouterException - Thrown if
$contextsisnulland attribute-based routing is disabled, if an empty array is passed, or if no route handler matches the current request context.
Note:The prefix name must be unique and reflect your URL structure accurately.Avoid mixing
Prefixobjects and array definitions in the same call, as it may lead to unintended errors.
Examples:
// Attribute-based routing:
Boot::http()->router->context()->run();// Method-based routing with Prefix objects:
use Luminova\Boot;
use Luminova\Routing\Prefix;
Boot::http()->router->context([
Prefix::with(Prefix::WEB, [AppError::class, 'onWebError']),
Prefix::with(Prefix::API, [AppError::class, 'onApiError']),
Prefix::with('admin', [AppError::class, 'onAdminError']),
Prefix::with(Prefix::CLI),
])->run();run
Execute application routes and handle incoming requests.
This method resolves the incoming HTTP or CLI request against the defined routes and dispatches it to the appropriate controller or handler. It finalizes application profiling, sends profiling data to the debugging UI, and triggers the onFinish application event before terminating the script with the resulting exit/status code.
public run(): voidThrows:
- \Luminova\Exceptions\RouterException – If an error occurs during request processing or route resolution, or if the router is invoked in the wrong context (e.g. calling an HTTP context from a CLI request or vice versa).
Note:
This method is typically invoked once in the
/public/index.phpfile, which serves as the application front controller.
pattern
Register a custom route placeholder with an optional grouping mode.
Allows you to replace placeholders like (:slug) with your own regex. You may choose whether the pattern should be raw, non-capturing, or capturing. This makes your routing clean, by providing an alias to a long pattern or repeatable patterns.
public static pattern(string $name, string $pattern, ?int $group = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | Placeholder name (e.g. slug). |
$pattern | string | Regular expression pattern (e.g. [a-z0-9-]+). |
$group | int|null | Grouping mode: - null: use pattern as-is.- 0: wrap as non-capturing group (?:pattern).- 1: wrap as capturing group (pattern).If the pattern already starts with (, no extra wrapping is applied. |
Throws:
- \Luminova\Exceptions\RouterException - If the placeholder name or pattern is empty, the name contains invalid characters, or the resulting placeholder is a reserved name (
(:root)or(:base)).
Examples:
Router::pattern('slug', '[a-z0-9-]+'); // raw pattern
Router::pattern('slug', '[a-z0-9-]+', 0); // non-capturing (?:[a-z0-9-]+)
Router::pattern('slug', '[a-z0-9-]+', 1); // capturing ([a-z0-9-]+)
Router::pattern('custom', '([a-z]+)-(\d+)', 1); // stays unchangedImportant:
Do not manually include outer start, end, or delimiter characters (e.g.,
^,$,#,/,~, etc.).The routing engine automatically appends them as needed when building the final route regex.
Implementations
HTTP Controllers:
- Learn how to handle HTTP requests and responses with the HTTP Routing Guide.
CLI Command Controllers:
- Learn how to define and route CLI commands with the CLI Routing Guide.