A really simple and small pathinfo php router
Install via Composer:
composer require stefanobalocco/damnsmallrouterOr add to composer.json:
{
"require": {
"stefanobalocco/damnsmallrouter": "^1.0"
}
}Run composer install or composer update.
use StefanoBalocco\DamnSmallRouter\Router;
$router = new Router();// Simple route with numeric placeholder
$router->AddRoute(
'/user/#09#', // Route pattern
function($userId) { // Callback - pattern parameters
$user = getUserFromDatabase($userId);
return renderUserProfile($user);
},
[], // Additional variables (optional)
'GET', // HTTP method (default: GET)
$isAuthorized // Route availability (optional)
);
// Route with additional variables
// Note: $variables are passed BEFORE pattern parameters
$router->AddRoute(
'/user/#09#',
function($isLogged, $userId) { // $isLogged from $variables, $userId from pattern
if (!$isLogged) {
return redirect('/login');
}
$user = getUserFromDatabase($userId);
return renderUserProfile($user);
},
[ isLogged() ] // This array becomes the first parameters
);
// Multiple methods for same route
$router->AddRoute('/profile', $profileGetHandler, [], 'GET');
$router->AddRoute('/profile', $profileUpdateHandler, [], 'POST');
// Conditional route availability
$router->AddRoute('/admin', $adminHandler, [], 'GET', userIsAdmin());Default error routes set HTTP response codes and return null. Customize them:
$router->AddRoute403(function() {
http_response_code(403);
return renderErrorPage("Access forbidden", 403);
});
$router->AddRoute404(function() {
http_response_code(404);
return renderErrorPage("Page not found", 404);
});
$router->AddRoute405(function() {
http_response_code(405);
return renderErrorPage("Method not allowed", 405);
});
$router->AddRoute500(function() {
http_response_code(500);
return renderErrorPage("Internal server error", 500);
});echo $router->Route(); // Display the routed page- Pattern matching with placeholder support
- Support for multiple HTTP methods
- Customizable error handling with automatic status codes
- Automatic HEAD request handling (converted to GET)
#09#: Numbers (\d+)#AZ#: Letters ([a-zA-Z]+)#AZ09#: Alphanumeric characters ([\w]+)
Adds a new route with:
$route: URL pattern with placeholders$callback: Function to execute (receives$variablesfirst, then pattern matches)$variables: Additional variables passed as first parameters to callback$method: HTTP method (GET, POST, PUT, DELETE, etc.)$available: Boolean condition for route availability
Checks if a route is available for the current path.
$method: HTTP method to check$withoutConditions: If true, ignores the$availableparameter of routes
Executes routing for the current request and returns the callback result.
AddRoute403($callback, $variables = []): Sets handler for forbidden accessAddRoute404($callback, $variables = []): Sets handler for not foundAddRoute405($callback, $variables = []): Sets handler for method not allowedAddRoute500($callback, $variables = []): Sets handler for internal server errors