A simple trie-based PHP router
Via composer:
composer require em4nl/urouter
Assuming you're using autoloading and your composer vendor dir is
at ./vendor
:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$router = new Em4nl\U\Router();
// set a base path if this app doesn't live at the root path
// (right behind the domain)
$router->base('/my-app');
$router->get('/', function() {
echo 'the index route';
});
$router->get('/test', function() {
echo "the /test route";
});
$router->get('/:thing', function($thing) {
echo "I like $thing!";
});
$router->get('/test/*', function($wildcard_match) {
// will match paths of arbitrary length behind /test/ ...
});
$router->post('/form', function($context) {
// ...
});
$router->catchall(function() {
header('HTTP/1.1 404 Not Found');
// ...
});
$router->run();
Routes don't have to be defined in any particular order, they will
be matched by specificity automatically. E.g. if you visit
/test/
, the /test
route will match and not the /:thing
route,
even if the latter would be defined earlier in the source code.
Install dependencies
composer install
Run tests
./vendor/bin/phpunit tests