Overview
TheRouter class is a lightweight, custom routing system that maps HTTP requests to controller actions. It provides a simple but powerful way to define routes without external dependencies.
Location: app/core/Router.php
The Router uses exact path matching and automatically handles base path normalization for subdirectory deployments.
Key Features
- HTTP method-based routing (GET, POST, etc.)
- Automatic base path detection for subdirectory installations
- Controller auto-loading and instantiation
- Built-in 404 error handling
- Zero external dependencies
Public Methods
add()
Registers a new route in the routing table.HTTP method (GET, POST, PUT, DELETE, etc.). Case-insensitive.
URL path to match (e.g.,
/login, /dashboard, /reservations/create)Name of the controller class (e.g.,
AuthController, DashboardController)Method name to call on the controller (e.g.,
showLogin, index, store)dispatch()
Processes the current HTTP request and routes it to the appropriate controller action.- Determines the current request path and HTTP method
- Searches through registered routes for a match
- Loads and instantiates the matching controller
- Calls the specified action method
- Returns a 404 error if no route matches
Implementation Details
Base Path Normalization
The Router automatically detects and strips the base path for applications installed in subdirectories:getCurrentPath() method:
Controller Loading
Controllers are loaded fromapp/controllers/ directory:
app/core/Router.php:65-82
The method:
- Checks if the controller file exists
- Requires the controller file
- Instantiates the controller class
- Verifies the action method exists
- Calls the action method
Error Handling
When no route matches, the Router returns a 404 response:app/core/Router.php:85-89
Complete Usage Example
routes/web.php:Design Philosophy
Unlike Laravel’s router which uses regular expressions for dynamic segments, this Router uses exact path matching. This makes it simpler but requires explicit routes for each endpoint.
- No regex parsing overhead
- Predictable routing behavior
- Easy to debug
- No external dependencies
- Cannot use route parameters like
/users/{id} - Each unique path needs its own route definition
- Query parameters must be handled manually in controllers
See Also
- Database Class - For database operations in controllers
- Auth Helper - For protecting routes
- Session Helper - For flash messages and session management