Routes with attributes and reflection

Mark controller methods with #[Route] and let reflection build the route table for you.

PHP · Routes with attributes and reflectionAdvanced
#[Attribute(Attribute::TARGET_METHOD)]
final class Route
{
    public function __construct(public string $path, public string $method = 'GET') {}
}

final class PageController
{
    #[Route('/hello')]
    public function hello(): string { return 'Hello'; }

    #[Route('/save', 'POST')]
    public function save(): string { return 'Saved'; }
}

function collectRoutes(string $class): array
{
    $routes = [];
    foreach ((new ReflectionClass($class))->getMethods() as $m) {
        foreach ($m->getAttributes(Route::class) as $attr) {
            $r = $attr->newInstance();
            $routes[$r->method . ' ' . $r->path] = [$class, $m->getName()];
        }
    }
    return $routes;
}

$routes = collectRoutes(PageController::class);
[$cls, $method] = $routes['GET /hello'];
echo (new $cls())->$method();
attributesreflectionroutingphp8