English · Français
studoo/edu-route maps an HTTP method and a URL to a handler (a controller name, a closure,
any value). It is the routing layer of edu-framework,
a framework built for teaching.
It is a modernized fork of nikic/FastRoute: same combined
regular-expression algorithm, rewritten for PHP 8.4 with enums, immutable result objects,
attribute routes, a route listing for routes:list commands, and static analysis at the
strictest level.
composer require studoo/edu-routePHP 8.4 or 8.5 is required.
<?php
require 'vendor/autoload.php';
use Studoo\EduRoute\ConfigureRoutes;
use Studoo\EduRoute\Dispatcher\Result\Matched;
use Studoo\EduRoute\Dispatcher\Result\MethodNotAllowed;
use Studoo\EduRoute\Dispatcher\Result\NotMatched;
use Studoo\EduRoute\EduRoute;
$router = EduRoute::recommendedSettings(
static function (ConfigureRoutes $r): void {
$r->get('/users', 'list_users');
$r->get('/user/{id:\d+}', 'show_user'); // {id} must be a number
$r->get('/articles/{id:\d+}[/{title}]', 'show_article'); // /{title} is optional
},
__DIR__ . '/var/cache/routes.php', // cache file
);
// Method and URI of the request, without the query string, decoded
$method = $_SERVER['REQUEST_METHOD'];
$uri = rawurldecode(strtok($_SERVER['REQUEST_URI'], '?'));
$result = $router->dispatcher()->dispatch($method, $uri);
echo match (true) {
$result instanceof Matched => $result->handler . ' ' . json_encode($result->variables),
$result instanceof MethodNotAllowed => '405 – allowed: ' . implode(', ', $result->allowedMethods),
$result instanceof NotMatched => '404 – not found',
}, "\n";Changes are listed in CHANGELOG.md.
make ci # coding standard, PHPStan (max level), Rector, PHPUnit
make phpbench # benchmarksOriginal code © Nikita Popov and the FastRoute contributors; modernization © Studoo. Released under the BSD-3-Clause license (LICENSE).