Routing

Learn how to use Kirby's built-in router class

Starting the router

$router = new Router();

Registering routes

Registering a single route

$router->register('api/users/(:any)', array(
  'method' => 'GET',
  'action' => function($username) {
    // the router action code
  }
));

Registering multiple routes

$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
    }
  )
));

Registering a route for multiple request methods

$router->register('api/users/(:any)', array(
  'method' => 'GET|POST|DELETE',
  'action' => function($username) {
    // the router action code
  }
));

Registering a route for all incoming requests

$router->register('api/users/(:any)', array(
  'method' => 'ALL',
  'action' => function($username) {
    // the router action code
  }
));

Available placeholders

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 placeholders

Optional attributes can be defined by adding a question mark to the placeholder:

Creating routing filters

$router->filter('auth', function() {
  // some authentication checks
});

Applying a filter to a route

$router->register('api/users/(:any)', array(
  'method' => 'ALL',
  'filter' => 'auth',
  'action' => function($username) {
    // the router action code
  }
));

Applying multiple filters to a route

$router->register('api/users/(:any)', array(
  'method' => 'ALL',
  'filter' => 'auth|someotherfilter',
  'action' => function($username) {
    // the router action code
  }
));

Run the router

if($route = $router->run()) {  
  $response = call($route->action(), $route->arguments());
}