Skip to content

silawrenc/traffic

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Traffic

High five

Master branch build status PHP ~7.0 Published version ISC Licensed

Traffic is lightweight, but fast and flexible php web routing component. Routes are defined as regular expressions and are dispatched to a stack of callable handlers.

The easiest way to install Traffic is via Composer.

{
    "require": {
        "silawrenc/traffic": "*"
    }
}

API

Adding routes

Routes can be added to the router in the format ($method, $pattern, ...$handlers) as follows.

$router = new Traffic;
$router->add('GET', '/foo/bar', function() {
    // do stuff
});

There are also convenience methods for GET and POST requests.

$router->get('/foo/bar', function () {
    // show stuff
});

$router->post('/foo/bar', function () {
    // save stuff
});

Dynamic routes

You can specify both the method and path as regular expressions. Captures are passed as positional arguments to handlers.

$router->add('(GET|POST)', '/user/([a-z]+)', function ($method, $username) {
    // as you were
});

A simpler syntax is also supported: you can use /foo/{bar} to capture part of a url (or method). The default is to match any characters except /. If you want to specify a pattern you can include it after a colon, e.g. /foo/{bar:\d{4}}. The wildcard * is supported for methods, and will match and capture any method name.

$router->add('*', '/foo/{bar}/{baz:[A-Z]+}', function ($method, $bar, $baz) {
    // important stuff
});

$router->add('(?:PATCH|PUT)', '/foo/{bar}', function ($bar) {
    // using a non-capturing regex group for the method
});

The best way to get a handle on supported formats is to have a look at passing and failing test cases. Anything that is a valid regular expression is a valid syntax for either method or path.

Handlers

You can specify as many handlers as you like, and they will be called in the order they are specified. If any handler returns strictly false, none of the handlers after it are invoked.

// return false from auth(), and render won't be invoked
$router->get('hello/world', auth(), render('landing'));

$router->get('hello/world', routeSpecificMiddleWare(), render('landing'), otherMiddleWare());

Routing

Once you've added all your routes, you can use the router for matching with:

$router->route($method, $path);

This will match $method and $path against all of the routes you've added, and invoke the handlers of the first match. So be sure to specify your routes from most to least specific. The return value of the route method is true if a match is found, and false if not.

About

A tiny, speedy regex powered router

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages