Luminova Framework

PHP Luminova: Request Routing, Resolution, and Handling

Last updated: 2026-11-28 20:57:12

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.

Luminova’s router matches incoming HTTP requests and CLI commands to a controller method or closure. HTTP middleware can run before a handler to check access or after a successful handler for follow-up work. Authentication checks belong in the middleware your application registers.

Luminova provides several optional routing features that can be enabled or disabled through the Environment Configuration (.env) file according to your application's requirements.


Supported Controllers

Routable controllers implement Luminova\Interface\RoutableInterface. The framework’s HTTP and CLI base controllers already implement it:


Route Definition Styles

Luminova supports both PHP Attribute and method-based route definitions, allowing you to choose the coding style that best fits your application.

Disabling and Enabling Attribute Routing

The project’s shipped .env enables attribute routing. If the setting is absent, the router falls back to false.

If you prefer to define routes manually using routing methods, disable attribute routing:

feature.route.attributes = false

Note:

Attribute routing and method-based routing cannot be used together. To use attribute routing, enable it in .env file with feature.route.attributes. To use method-based routing, you must disable attribute routing.


Attribute Routing 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

PHP attribute classes for routing includes optional optimizations for route resolution and production caching. These reduce the need to re-scan and re-parse attributes on every request.

Caching Attributes

For performance in production, you can cache route attributes to prevent them from being parsed on every request:

feature.route.cache.attributes = true

Note:

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 discovery and performance:

route.optimize.attributes = true

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

use Luminova\Routing\Router;

Router::get('/', 'MainController::index');

Router::get('/', function (): int {
    return STATUS_SUCCESS;
});

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.

URI-Prefix Routes Definition Grouping

Route prefix groups allow the routing system to load only the route definitions associated with the current request URI prefix 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 current working directory.
 */
if (getcwd() . DIRECTORY_SEPARATOR !== DOCUMENT_ROOT) {
    chdir(DOCUMENT_ROOT);
}

/**
 * Define routing contexts.
 */
Boot::http()->router->context([
    Prefix::with(Prefix::CLI, isCommand: true),                                 // 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 URI prefix, create a corresponding route file in /routes/ and define all user related routes.

In /routes/user.php

// /routes/user.php

use Luminova\Routing\Router;

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 URI prefix that matches user, are scanned only in routes/user.php, reducing route scanning overhead and improving response time.

GET https://example.com/user/peter

Routable Handlers Return Format

Luminova routing supports different return types from routable handlers, depending on whether the request/controller 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 Controller's Response Objects

The HTTP controller's 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.

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
    );
}

HTTP Response Classes

The following built-in response classes are available:

  • Luminova\Http\Message\Response — PSR-7 HTTP response implementation that implements Psr\Http\Message\ResponseInterface.
  • Luminova\Template\Response — Template response implementation that implements Luminova\Interface\ContentResponseInterface.

Note:

Response objects are supported only by HTTP controller methods and closure handlers. CLI command handlers must return an integer status code.


Controller's Response Integers

The Integer Status Codes provide the simplest way to indicate that a handler successfully processed a request, failed or handled failure gracefully from a routable handlers. They are commonly used with the Template View Class, whose rendering methods return an int, and are required for CLI command handlers.

Luminova uses these integer constants to decide how to continue routing:

  • STATUS_SUCCESS - value 0, both HTTP and CLI.
  • STATUS_ERROR - value 1, both HTTP and CLI.
  • STATUS_SILENCE - value 2, supported in HTTP only.

These are framework routing statuses. Set the HTTP response status separately when sending the response.

HTTP Handler's Response Status Code Responsibilities

  • STATUS_SUCCESS

    • Regular handler: Indicates that a request was handled successfully.
    • Middleware handler: Indicates that a middleware check passed and routing should continue processing.
  • STATUS_ERROR

    • Regular Handler: Indicates that a request failed and the routing system should trigger an error response.
    • Middleware Handler: Indicates that a middleware check failed, routing stops, and the router calls onMiddlewareFailure() when the middleware is a controller method.
  • STATUS_SILENCE

    • Regular Handler: Indicates that a request was handled internally, such as when a custom error response has already been displayed.
    • Middleware Handler: Behaves like STATUS_ERROR, but skips Controller::onMiddlewareFailure() and stops routing. Use STATUS_SUCCESS or STATUS_ERROR for middleware whenever possible.

CLI Handler's Response Status Code Responsibilities

In CLI controller's handlers method and closure handlers must return an integer exit code.

  • STATUS_SUCCESS — Indicates that a command or middleware check completed successfully.
  • STATUS_ERROR — Indicates that a 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, calling Luminova\Luminova::terminate(), or using exit.


Dependency Injection Resolving

Luminova provides dependency injection resolver for routable controller methods and closure handlers through the Luminova\Routing\DependencyResolver 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() and Router::group() closure handlers.
  • Error handler closures Router::onError().
  • Error controller classes that implement Luminova\Interface\ErrorControllerInterface.

The project’s shipped .env enables routing dependency injection. If the setting is absent, the router falls back to false. To enable it, set:

feature.route.dependency.injection = enable

See the Dependency Injection documentation for detailed examples and supported dependency types.


Registering Dependencies

To register a custom dependency binding, use DependencyResolver::bind() or the application's bind() method.

Bindings can be registered from:

  • A controller's onCreate() method.
  • The application's onPreCreate() or onCreate() method.
  • /app/Utils/Global.php when feature.app.dev.functions is 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\Service\UserService;
use App\Service\ReportService;
use App\Service\AbstractUserService;

protected function onCreate(): void
{
    $this->bind(AbstractUserService::class, UserService::class);

    $this->bind(
        ReportService::class, 
        fn(): ReportService => new ReportService()
    );
}

A handler that type-hints AbstractUserService receives a UserService instance. The separate ReportService binding illustrates registering a concrete class under its own name. Both implementation classes should be instantiable without constructor arguments.


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 Luminova\Attributes\Route;
use App\Service\AbstractUserService;

#[Route('/user/(:int)')]
public function profile(int $userId, AbstractUserService $user): int
{
    $user->setIdentifier($userId);

    return $this->send([
        'id' => $user->id,
        'name' => $user->name
    ]);
}

Route closure:

// /routes/user.php

use Luminova\Routing\Router;
use App\Service\AbstractUserService;
use function Luminova\Funcs\response;

Router::get('/user/(:int)', function (int $userId, AbstractUserService $user): int {
    $user->setIdentifier($userId);

    return response()->json([
        'id' => $user->id,
        'name' => $user->name
    ]);
});

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 profile(
    UserService&AbstractUserService $user
): int {
    return STATUS_SUCCESS;
}

The injected object must implement all interfaces specified by the intersection type.

Examples:

interface LoggerInterface
{
    public function log(string $level, string $message): void;
}

interface FormatterInterface
{
    public function format(string $message): string;
}

class Logger implements LoggerInterface, FormatterInterface
{
    public function log(string $level, string $message): void
    {
        file_put_contents("{$level}.log", $message);
    }

    public function format(string $message): string
    {
        return strtoupper($message);
    }
}

Register the implementation with the dependency resolver:

// /app/Application.php

protected function onCreate(): void
{
    $this->bind(
        LoggerInterface::class,
        Logger::class
    );
}

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's handler methods or closure handlers.

Captured parameters can be combined with dependency injection, allowing additional dependencies to be automatically injected into the handler.

use App\Models\Product;

#[Route('/order/(:int)')]
public function order(int $oid, Product $product): int
{
    return STATUS_SUCCESS;
}

Register the equivalent route in a method-based context with the route pattern as the first argument.

use App\Models\Product;
use Luminova\Routing\Router;

Router::get('/order/(:int)', function (string $oid, Request $product): int {
    return STATUS_SUCCESS;
});

There are several ways to define capture patterns, including named placeholder (e.g, {oid}) and regex patterns.


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).

Defining a Custom Pattern 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)')]
public function post(string $slug): int
{
    return STATUS_SUCCESS;
}

Note:

Register custom patterns in the application class's onPreCreate() or onCreate() method. This ensures the patterns are registered before the routing system begins processing requests.


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}

URI Segment Object

The Luminova\Routing\Segments class provides APIs to access the current request's URI segments. The object is returned by Router::getSegment().

In CLI mode, it contains a single synthetic segment.

Example:

$segments = Router::getSegment();

echo $segments->position(0);
echo $segments->toString();

For more information, see the Request URI Segments documentation.


Class Definition


Documentation Reference

The methods below are shared between HTTP and CLI routing. For context-specific APIs documentation (route registration shorthands, middleware, commands), see HTTP Routing and CLI Routing.


Shared Methods

__construct

Initializes the router. When $app is omitted, the shared application instance is resolved from the framework kernel.

public function __construct(?AbstractApplication $app = null)

setApplication

Assign the application instance used by the router.

public function setApplication(AbstractApplication $app): self

addNamespace

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 of App\Modules\Blog\Controllers\Http.This allows the routing system to capture and resolve both Http and Cli namespaces under the registered group.
public function addNamespace(string $namespace): self

Parameters:

ParameterTypeDescription
$namespacestringThe namespace to register (e.g., App\Controllers\, App\Modules\Blog\Controllers\).

Return:

self - Returns the instance of the router class.

Throws:

Example:

Registering namespaces for HMVC module controllers, typically inside your application's onCreate():

// /app/Application.php
namespace App;

use Luminova\Foundation\Core\AbstractApplication;

class Application extends AbstractApplication
{
    protected function onCreate(): void
    {
        // Register HMVC module namespaces
        $this->router
            ->addNamespace('\\App\\Modules\\Admins\\Controllers\\')->addNamespace('\\App\\Modules\\Users\\Controllers\\');
    }
}

Note:

For MVC and HMVC applications, the default root controllers namespace are already defined in the Luminova\Foundation\Core\AbstractApplication class.Use addNamespace only to extend routing for additional custom HMVC module controllers.


getNamespaces

Get the registered controller namespaces.

public static function getNamespaces(): array

Return:

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 initialization and optimization strategy. It initializes and resolves routes based on the request URI prefix, allowing the framework to load only the relevant route when using method-based routing (e.g, routes/web.php, routes/api.php, or routes/cli.php) at runtime.

This 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 function context(?array $contexts = null): self

Parameters:

ParameterTypeDescription
$contextsarray<array-key,Prefix&#124;array{prefix:string,onError?:Closure&#124;array{0:class-string,1:string}&#124;null,isCommand?:bool}>&#124;nullA list of context definitions for method-based routing. Omit the list when attribute routing is enabled.

Return:

self - Return router instance class.

Throws:

Examples:

Attribute Routing Context:

Leave the context argument blank or set null when attribute routing is enabled.

// Attribute-based routing:
Boot::http()->router->context()->run();

Method-Based Routing Context:

Optionally configure URI-prefix grouping when using method based routing.

// Method-based routing with Prefix objects:
use Luminova\Boot;
use Luminova\Routing\Prefix;
use App\Errors\Controllers\AppError;

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, isCommand: true),
])->run();

Note:The prefix name must be unique and reflect your URL structure accurately.Avoid mixing Prefix objects and array definitions in the same call, as it may lead to unintended errors


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 function run(): void

Throws:

  • 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.php file, 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 function pattern(string $name, string $pattern, ?int $group = null): void

Parameters:

ParameterTypeDescription
$namestringPlaceholder name (e.g. slug).
$patternstringRegular expression pattern (e.g. [a-z0-9-]+).
$groupint|nullGrouping 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 unchanged

Important:

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:

  • CLI Command Controllers: