Routing
Learn how to create routes based on closures, functions, methods, controllers and also how to isolate routes in different scopes.
Create routes
{placeholder} $app->action(method, path, callback)
$app->action('GET', '/hello', function () {
echo 'Hello world!';
});
{placeholder}
$app->action('GET', '/hello', function () {
return 'Hello world!';
});
{placeholder}
function sample() {
echo 'Hour server: ', date('h:i:s');
}
$app->action('GET', '/hello', 'sample');
{placeholder}
class Sample {
public function method() {
echo 'Hello!';
}
}
$instance = new Sample();
$app->action('ANY', '/', [$instance, 'method']);
{placeholder}
$app->action('GET', '/say', 'Foo\Bar\BazController::method');
Static method
$app->action('GET', '/static', ['Foo\Bar\BazController', 'hello']);
{placeholder} system/controllers/Foo/Bar/BazController.php
<?php
namespace Controller\Foo\Bar;
class BazController
{
public function method()
{
echo '{placeholder}';
}
public static function hello()
{
echo '{placeholder}';
}
}
Scope routes
Routes only HTTPS
$app->scope('https://*', function () {
$app->action('GET', '/', function () {
return '"Hello World" running on HTTPS';
});
});
Routes only HTTP
$app->scope('http://*', function () {
$app->action('GET', '/', function () {
return '"Hello World" running on HTTP';
});
});
Pattern routes
{placeholder}
$app->action('GET', '/foo/<foo>/<bar>', ...);
$app->action('GET', '/foo/<foo>-<bar>', ...);
// Example: http://localhost:8000/article/foo-1000
$app->action('GET', '/article/<name>/<id>', ...);
{placeholder}
// Example: http://localhost:8000/blog/foo-1000
$app->action('GET', '/blog/<name>-<id:num>', ...);
// Example: http://localhost:8000/test/foo-1000
$app->action('GET', '/test/<id:num>', ...);
{placeholder}
// Example: http://localhost:8000/test/foo/abc
$app->action('GET', '/test/foo/<name:alpha>', ...);
{placeholder}
Pattern | Regex used | Description |
---|---|---|
:alnum |
[\da-zA-Z]+ |
Matches routes or scope param with alpha-numeric |
:alpha |
[a-zA-Z]+ |
Matches routes or scope param with A to Z letters |
:decimal |
(0|[1-9]\d+)\.\d+ |
Matches routes or scope param with decimal format (like 1.2, 3.5, 100.50) |
:nospace |
[^/\s]+ |
Matches routes or scope param with any characters expcet spaces, like white-spaces (%20 ), tabs (%0A ) and others (see about \S in regex) |
:num |
\d+ |
Matches routes or scope param with numeric format |
:uuid |
[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12} |
Matches routes or scope param with UUID format |
:version |
\d+\.\d+(\.\d+(-[\da-zA-Z]+(\.[\da-zA-Z]+)*(\+[\da-zA-Z]+(\.[\da-zA-Z]+)*)?)?)?' |
Matches routes or scope param with semver.org format |