Learn how to use Kirby's built-in router class
$router = new Router();
$router->register('api/users/(:any)', array(
'method' => 'GET',
'action' => function($username) {
// the router action code
}
));
$router->register(array(
array(
'pattern' => 'api/users/(:any)',
'method' => 'GET',
'action' => function($username) {
// the router action code
}
),
array(
'pattern' => 'api/users/(:any)',
'method' => 'DELETE',
'action' => function($username) {
// the router action code
}
)
));
$router->register('api/users/(:any)', array(
'method' => 'GET|POST|DELETE',
'action' => function($username) {
// the router action code
}
));
$router->register('api/users/(:any)', array(
'method' => 'ALL',
'action' => function($username) {
// the router action code
}
));
URL patterns for routes can be static, relative URLs: some/static/url
or parts of the URL can be defined by dynamic placholders:
Placeholder | Matches |
---|---|
(:any) | Matches any character and stops at the next / |
(:num) | Matches any number and stops at the next / |
(:all) | Matches everything from here on until the end or the next placeholder |
Placeholders can also contain expressions. I.e. ([a-z]+)
Placeholders will be passed as arguments in the order they appear.
// my/awesome/pattern/(:any)/(:num)/(:all)
function($anyPlaceholder, $numPlaceholder, $allPlaceholder) {
};
Optional attributes can be defined by adding a question mark to the placeholder:
$router->filter('auth', function() {
// some authentication checks
});
$router->register('api/users/(:any)', array(
'method' => 'ALL',
'filter' => 'auth',
'action' => function($username) {
// the router action code
}
));
$router->register('api/users/(:any)', array(
'method' => 'ALL',
'filter' => 'auth|someotherfilter',
'action' => function($username) {
// the router action code
}
));
if($route = $router->run()) {
$response = call($route->action(), $route->arguments());
}