PHP code example of stefanobalocco / damnsmallrouter
1. Go to this page and download the library: Download stefanobalocco/damnsmallrouter library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
stefanobalocco / damnsmallrouter example snippets
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());