Joel Vardy

RESTful Routes

Posted: 26 June 2013

A Composer package which allows you to easily map routes to a block of code. This is an ideal base for small websites and RESTful APIs.

Update: this is not a perfect library, you may want to consider using the Slim micro framework, which is usually what I now find myself using.

Requiring the Package

I'm not going to explain how to use composer, if you are not sure then read the manual.

Open your composer.json file and require the routes package.

"require": {
    "joelvardy/routes": "v1.1"
}

Then ensure you run the composer update command.

Instantiating the Library

Ensure you have the composer autoloading setup, then you just need to instantiate the library by adding $routes = new Joelvardy\Routes(); - at this point your file should look something like:

// Autoload Composer
require('vendor/autoload.php');

// Instantiate routes library
$routes = new Joelvardy\Routes();

echo 'Hello Routes!';

Adding a Route

Now we are going to add a route to create a new user account, because we are creating something we will POST to our API endpoint.

$routes->post('/user', function () {
    // Add the user to the database
    $user->create($_POST['username'], $_POST['password'], $_POST['email']);
});

As you might imagine you can use a different REST method by substituting $routes->post( with any of the accepted methods: GET, POST, PUT, PATCH, and DELETE.

Regular Expressions

You will generally have dynamic routes for example, the URI in your browser at the moment ends /writing/restful-routes usually you will want to grab that slug and read an item from your database which is associated with it.

You can do this using regular expressions, for example:

$routes->get('/user/([a-zA-Z0-9-_]+)', function ($username) {
    // Check the username exists
    if ( ! $users->read_by_username($username)) return false;
    echo 'Read specific user, username: '.$username;
});

Custom 404 Error

In the above example you can see we check whether the user exists, and if not we return false. Returning false from the anonymous function will cause a 404 error to be returned.

We can add a special route which is run if no routes are matched, or if a matching route returns false.

$routes->notFound(function () {
    echo 'Error 404 :(';
});

Running the Routes

After adding the routes you must run $routes->run(); this is easily forgotten, but without it none of the routes will run.

Use It!

So, there you have it, you can view the Composer package on GitHub which has a complete usage example.