Very basic routing class
Very basic routing class (about 103 lines) ..., (*1)
Bob::get($pattern, $callback);
is short for, (*2)
Bob::add('get', $pattern, $callback);
$method
and $pattern
can either be strings or arrays of strings. $callback
s are one or more functions or a class., (*3)
Bob::go($file);
Add a route:, (*4)
Bob::get('/', function() { echo 'Hello World'; });
A little bit more:, (*5)
Bob::get('/user/bob', function() { echo 'Hey, bob!'; });
Add a bunch of patterns:, (*6)
Bob::get(['/', '/home'], function() { echo 'Hello World'; });
Use a function:, (*7)
Bob::get('/user/:is_numeric', function($id) { echo 'Hello, '.$user[$id]; });
Use an own function:, (*8)
Bob::get('/user/:is_user', function($user) { echo 'Hey, '.$user.'!'; }); function is_user($user) { return in_array($user, ['Justus', 'Peter', 'Bob']); }
Negate:, (*9)
Bob::get('/user/:is_user', function($user) { echo 'Hey, '.$user.'!'; }); Bob::get('/user/!is_user', function($user) { echo 'Can\'t find this user :('; });
You can also use regex (in the same way you'd use a function):, (*10)
Bob::$patterns = [ 'num' => '[0-9]+', 'all' => '.*' ]; Bob::get('/:num', function($id) { echo $id; });
Use multiple callbacks:, (*11)
Bob::get('/user/:is_numeric', [function($id) { echo 'Hello, '.$user[$id]; }, count_login($id)]);
Multiple request methods:, (*12)
Bob::add(['post', 'put'], '/user', function() { // Add a user! Or something else! I don't care! });
Your can also use a class as callback. Just pass its name. Bob will try to execute $method
on $callback
, so something like this will work:, (*13)
class SayHello { static function get($num) { for($i = 0; $i < $num; $i++) echo 'GET Hello!'; } static function post($num) { for($i = 0; $i < $num; $i++) echo 'POST Hello!'; } }
Bob::add([], '/:is_numeric', 'SayHello');
Notice that you have to use Bob::add()
with an empty array. In this case, you're not required to tell Bob the accepted HTTP methods, it'll just look inside the provided class., (*14)
With the use-an-own-function-example from above, the (second) final step could look like this:, (*15)
Bob::go();
Or - if you'd like to work in a subdirectory - trim the request url:, (*16)
Bob::go('/foo/bar.php');
http://localhost/foo/bar.php/user/1
=>
/user/1
, (*17)
404:, (*18)
Bob::summary(function($passed, $refused) { echo $passed.' routes passed, '.$refused.' were refused.'; });
This will only execute the callback, if no rule matched the request:, (*19)
Bob::notfound(function($passed, $refused) { echo '404 :('; });
You're done. Have a nice day., (*20)