To set up a certain route in Pagenode, you simply call the route() function with the path and a callback function that will handle this route.
route('/my-path', function() {
// Handle all requests to /my-path
});
Once you have defined all routes, you can call the dispatch() function. If you don't provide a path, the path will be determined from the current request URL (relative to your index.php). This will probe all routes in order to find a matching route.
dispatch();
Note that only the path component of the URL will be matched against your routes by default. I.e. the URL example.com/my-path?foo=bar will still match the route defined above.
If no matching route can be found, a default 404 handler will be called. It is good practise to define your own 404 handler with a simple catch-all route:
route('/*', function() {
// Handle all requests that didn't match any previous route
});
Routes can have any number of parameters. Parameters are defined by an identifier in curly braces (e.g {name}) in your route. These parameters will be passed to your callback function. A parameter can be any value not containing a / (forward slash). E.g.:
route('/foo/{bar}/{baz}', function($bar, $baz) {
echo htmlSpecialChars("bar: $bar, baz: $baz");
});
If a parameter is defined in your route, it must match something. E.g. the route above will match /foo/lorem/ipsum but not /foo/lorem or /foo/lorem/ipsum/dolor.
If you determine that a request cannot be fulfilled in a route handler, you can simply return false and the request will be passed on to your /* handler or if this fails as well, to the default 404 handler.
route('/blog/{keyword}', function($keyword) {
$node = select('nodes/blog/')->one(['keyword' => $keyword]);
if (!$node) {
return false; // Will be handled by the /* route
}
include('templates/node.html.php');
});
To re-route a request internally you can call reroute(). This will not redirect the user, but just internally forward the request.
reroute('/', '/my-path');
Up Next: Presenting »