Router
The Router class handles HTTP routing for GET and POST requests, supporting dynamic route parameters and middleware integration.Namespace
Methods
get()
Registers a GET route with a controller, method, and optional middleware.The URL endpoint pattern (supports dynamic parameters like
/edit/{id})The fully qualified controller class name
The controller method to invoke
Optional middleware class name to execute before the controller
Example
post()
Registers a POST route with a controller, method, and optional middleware.The URL endpoint pattern (supports dynamic parameters like
/update/{id})The fully qualified controller class name
The controller method to invoke
Optional middleware class name to execute before the controller
Example
dispatch()
Dispatches the request to the appropriate controller based on the current HTTP method and URI.This method handles the routing logic internally and either:
- Executes the matched route’s controller method
- Renders a 404 page if no route matches
- Renders a 403 page if middleware denies access
Behavior
- Extracts
REQUEST_METHODandREQUEST_URIfrom the server - Strips query strings from the URI
- Matches dynamic routes with placeholders (e.g.,
/user/{id}) - Passes extracted parameters to the controller method
- Tracks previous and current URLs in session
- Sanitizes POST data (except for
contentfield) - Renders
404.htmlif no route matches
Example
matchDynamicRoute()
Matches a defined route pattern against the current request URI and extracts parameters.The route pattern with placeholders (e.g.,
/user/{id}/post/{postId})The actual requested URI path
Passed by reference - will be populated with extracted route parameters
Returns
true if the route matches, false otherwiseHow It Works
- Converts route placeholders
{param}to regex capture groups([^/]+) - Performs regex match against the current route
- Extracts matched parameters into the
$paramsarray - Returns
trueon successful match
Example
Properties
Private Properties
- $getRoutes: Stores all registered GET routes as an associative array
- $postRoutes: Stores all registered POST routes as an associative array
Middleware Support
Middleware classes must implement ahandle() method that returns:
trueto allow the request to proceedfalseto deny access (renders 403.html)- Any other value to redirect to the previous URL