joelvardy/routes

Simple RESTful routing

Installs: 228

Dependents: 0

Stars: 6

Watchers: 1

Open Issues: 1

Language: PHP

v1.1 2013-03-26 11:59 UTC

README

Created by Joel Vardy, this library allows you to specify RESTful routes.

Installation

Add the following to your composer.json require object:

"joelvardy/routes": "dev-master"

Usage

Trailing Slashes - The examples here assume that trailing slashes are stripped.

An example showing a few routes:

// Initialise routes
$routes = new Joelvardy\Routes();

// Homepage
$routes->get('/', function () {

    echo 'Homepage';

});

// Read specific user
$routes->get('/user/([0-9]+)', function ($userId) {

    echo 'Read specific user, ID: '.$userId;

});

// New user
$routes->post('/user', function () {

    echo 'New user';

});

// If no other routes match
$routes->notFound(function () {

    echo 'Error 404 :(';

});

// Run routes
$routes->run();

Throw HTTP 404

You can call the notfound routes from within route, by returning false from the callback, for example:

// Match any strings
$routes->get('/([a-z]+)', function ($string) {

    $allowedStrings = array(
        'joel',
        'vardy',
        'developer'
    );

    if ( ! in_array($string, $allowedStrings)) {
        return false;
    }

    echo 'Allowed string: '.$string;

});

Order

The order of routes may be important, for example in the example above where we are matching any string of letters, if you also wanted a route to match /contact you would need to run that afterwards.

Allowed Request Methods

The allowed request methods are:

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • TRACE
  • OPTIONS
  • CONNECT
  • PATCH

These can be run like so:

$routes->patch('/user/([0-9]+)', function ($userId) {

    echo 'Selectively update the user with ID: '.$userId;

});