• The basics

Routing

HTTP Routes enable you to determine what to display based on the URL the user has requested.

To do this, you can use the Router class.

Quick example

use Includable\HTTP\Router;

$router = new Router();

$router->get('/ping', function() {
  return 'pong';
});

Basic routing

The Router class has 4 main methods, corresponding to the HTTP request methods that can be used to execute a request:

  • get
  • post
  • put
  • delete

Each of these methods accept two parameters: a $path and a $callback.

Matching everything

There's also method called any, which can be used to catch all request methods. It is also special since it allows you to omit the first parameter to match any path and any request method.

Executed in order

The router will execute the first matching path and method combination it comes across. That means that it stops routing after the first match is found.

The example below will for that reason only execute the /ping route, not the second, even though both match a URL that ends in /ping:

$router->get('/ping', function() {
  return 'pong';
});
$router->any(function() {
  return 'something else';
});

Parameters

It is possible to have routes that contain variables in the URL. These will be passed, in order from left to right, to the callback:

$router->get('/shops/:shop/products/:product/', function($shop, $product) {
  return 'The page for product ' . $product . ' in shop ' . $shop;
});

Callback types

So far we've been using only anonymous functions as our $callback parameter. It's also possible to used named functions:

function get_post($id) {
  echo 'Post ID: ' . $id;
}

$router->get('/posts/:id', 'get_post');

Or even class methods:

class Posts {
  public function getPost($id) {
    echo 'Post ID: ' . $id;
  }
}

$router->get('/posts/:id', 'Posts@getPost');

Prefixes

If you have many routes with the same prefix, you can group them like so:

$router->withPrefix('posts', function($router) {
  $router->get('/', 'Posts@getAll'); // matches `/posts`
  $router->get('/:id', 'Posts@getPost'); // matches `/posts/:id`
});

Namespaces

If you're using class methods as your callbacks, you can define a namespace to look into for your classes:

$router->setNamespace('\\MyModule\\Routes');

$router->get('posts/:id', 'Posts@getPost');
  // Will search for a class named `\MyModule\Routes\Posts`

Return values

Your route callback doesn't have to return anything, but if it does return an array or object, it will automatically be converted to JSON, making it super easy to build an API:

$router->get('/v1/rockets/falcon-heavy', function() {
  return [
    'name' => 'Falcon Heavy',
    'boosters' => 3,
    'launched' => 2018
  ];
    // Will result in this JSON output:
    // {"name":"Falcon Heavy","boosters":3,"launched":2018}
});