set404(function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '404, route not found!';
});
// custom 404
$router->set404('/test(/.*)?', function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '
404, route not found!
';
});
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
// Before Router Middleware
$router->before('GET', '/.*', function () {
header('X-Powered-By: bramus/router');
});
// Static route: / (homepage)
$router->get('/', function () {
echo 'bramus/router
Try these routes:
Custom error routes
';
});
// Static route: /hello
$router->get('/hello', function () {
echo 'bramus/router
Visit /hello/name to get your Hello World mojo on!
';
});
// Dynamic route: /hello/name
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . htmlentities($name);
});
// Dynamic route: /ohai/name/in/parts
$router->get('/ohai/(.*)', function ($url) {
echo 'Ohai ' . htmlentities($url);
});
// Dynamic route with (successive) optional subpatterns: /blog(/year(/month(/day(/slug))))
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if (!$year) {
echo 'Blog overview';
return;
}
if (!$month) {
echo 'Blog year overview (' . $year . ')';
return;
}
if (!$day) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if (!$slug) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Subrouting
$router->mount('/movies', function () use ($router) {
// will result in '/movies'
$router->get('/', function () {
echo 'movies overview';
});
// will result in '/movies'
$router->post('/', function () {
echo 'add movie';
});
// will result in '/movies/id'
$router->get('/(\d+)', function ($id) {
echo 'movie id ' . htmlentities($id);
});
// will result in '/movies/id'
$router->put('/(\d+)', function ($id) {
echo 'Update movie id ' . htmlentities($id);
});
});
// Thunderbirds are go!
$router->run();
// EOF