1. Go to this page and download the library: Download weew/router 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/ */
$router = new Router();
$router->get('home/{greeting?}', 'home');
$route = $router->match(HttpRequestMethod::GET, new Url('home/welcome'));
echo $route->getParameter('greeting');
// welcome
$router = new Router();
$router->get('home/{greeting?}', 'home');
$route = $router->match(HttpRequestMethod::GET, new Url('home/hello-there'));
if ( ! $route === null) {
echo $route->getAction();
// home
echo $route->getParameter('greeting');
// hello-there
} else {
// no route found, thow a 404?
}
$router = new Router();
$router
->addPattern('id', '[0-9]+')
->get('users/{id}', '');
$router = new Router();
$router->addFilter('auth', function(IRoute $route) {
// returning false indicates that filter has failed, no other filters will be called
return false;
});
$router->addFilter('guest', function(IRoute $route) {
// explicitly returning true indicates that this route is ok, no other filters will be called
return true;
});
$router->enableFilter('auth');
$router->enableFilter('guest');
// or
$router->enableFilter(['auth', 'guest']);
$router = new Router();
$router->addFilter('auth', function(IRoute $route) {
throw new FilterException(
new UnauthorizedException()
);
});
$router = new Router();
$router->addResolver('user', function($parameter) {
return new User(); // for the sake of the example lets just return a new model
});
$router->get('users/{user}', function(User $user) {
// work with the user model
});
$router = new Router();
$router
->restrictSubdomain('api')
->get('users/{id}', '');