ziraphp / router
Attribute routing and route caching for ZiraPHP.
Requires
- php: >=8.2
- ziraphp/framework: ^0.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- phpstan/phpstan: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^11.5
- squizlabs/php_codesniffer: ^3.10
- vimeo/psalm: ^6.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Attribute routing and route caching for ZiraPHP.
- Declare routes next to the code that handles them with
#[Get],#[Post]and friends, a class-wide#[Prefix]and#[Middleware]. - Load a whole controller directory in one call.
- Cache every route, attribute-based or not, into one PHP file for production.
Routes are registered on ZiraPHP's own router (any RouterInterface), so
matching, URL generation, handlers and middleware work exactly as described in
the core routing guide.
composer require ziraphp/router
Requires PHP 8.2+ and ziraphp/framework ^0.1.
Attribute routes
namespace App\Controller; use ZiraPHP\Router\Attribute\Delete; use ZiraPHP\Router\Attribute\Get; use ZiraPHP\Router\Attribute\Middleware; use ZiraPHP\Router\Attribute\Post; use ZiraPHP\Router\Attribute\Prefix; use ZiraPHP\Router\Attribute\Route; #[Prefix('/posts', name: 'posts.')] #[Middleware('auth')] final class PostController { #[Get('/', name: 'index')] public function index(): array { /* ... */ } #[Get('/new', name: 'create', priority: 10)] // before /posts/{id} public function create(): string { /* ... */ } #[Get('/{id:\d+}', name: 'show')] public function show(int $id): array { /* ... */ } #[Post('/')] #[Middleware('csrf')] public function store(): array { /* ... */ } #[Route('/{id:\d+}', methods: ['PUT', 'PATCH'], name: 'update')] public function update(int $id): array { /* ... */ } #[Delete('/{id:\d+}', middleware: 'audit')] public function destroy(int $id): null { /* ... */ } }
use ZiraPHP\Router\AttributeLoader; $loader = new AttributeLoader(); $loader->load($app->getRouter(), PostController::class, CommentController::class); // or every class in a PSR-4 directory: $loader->loadDirectory($app->getRouter(), __DIR__ . '/../src/Controller', 'App\\Controller');
$router->generate('posts.show', ['id' => 7]) returns /posts/7.
| Attribute | Where | Effect |
|---|---|---|
#[Get], #[Post], #[Put], #[Patch], #[Delete], #[Options], #[Any] |
method or class | A route for that method; #[Get] also answers HEAD. Arguments: path, name, middleware, priority. |
#[Route(path, methods: [...])] |
method or class | A route for any methods. |
#[Prefix('/admin', name: 'admin.')] |
class | Prefixes every path, and the name of every named route. |
#[Middleware('auth', 'csrf')] |
class or method | Container ids of PSR-15 middleware. |
Route attributes are repeatable, so one method can answer several paths.
- Middleware order: class
#[Middleware], then method#[Middleware], then the route attribute'smiddleware:. Global and group middleware run before all of these, as in the core router. - Class-level routes make the class itself the handler. The class must be
invokable or a PSR-15
RequestHandlerInterface. - Inheritance: routes declared on a parent class's methods are registered for each concrete subclass that is loaded, with the subclass as the handler. Abstract classes are not loaded on their own.
- Errors: a route on a private method, a constructor, an abstract class or a
class that cannot be called throws
InvalidRouteExceptionwhen the class is loaded, not when a request arrives.
Route order
Routes match in the order they are registered. The loader registers them by
descending priority (default 0), then class by class in the order given (or
by file path for loadDirectory()), then in declaration order within a class.
Give static paths such as /posts/new a higher priority than
/posts/{slug}, or constrain the parameter ({id:\d+}).
Directory loading
loadDirectory() maps files to classes with PSR-4 rules:
src/Controller/Admin/UserController.php becomes
App\Controller\Admin\UserController. Classes are loaded through the
autoloader. Files that hold no matching class, and abstract classes,
interfaces, traits and enums, are skipped.
Route cache
Reflection and directory scans cost time on every request. RouteCache
stores the finished route list in a PHP file that OPcache keeps in memory:
use ZiraPHP\Interfaces\Routing\RouterInterface; use ZiraPHP\Router\AttributeLoader; use ZiraPHP\Router\RouteCache; $cache = new RouteCache($app->basePath('var/cache/routes.php')); $cache->remember($app->getRouter(), function (RouterInterface $router): void { (new AttributeLoader())->loadDirectory($router, __DIR__ . '/../src/Controller', 'App\\Controller'); $router->get('/health', HealthHandler::class); $router->group('/api', function (RouterInterface $router): void { $router->get('/users/{id:\d+}', [UserController::class, 'show'])->name('api.users.show'); }, ['cors']); });
When the cache file exists, remember() registers its routes and never calls
the callback. Otherwise it runs the callback against a fresh router, writes
the cache and registers the routes. Group prefixes and middleware are
preserved. Call it outside any router group, since cached paths are already
complete.
- Refreshing: the cache is used as-is until cleared. Write it during
deployment and call
clear()(or delete the file) when routes change. Leave it off in development. - What can be cached: handlers must be a class name,
"Class::method"or[Class::class, 'method'], and middleware must be container ids. A closure or object makesremember()andwrite()throwRouteCacheExceptionnaming the route; no file is written. - Damaged or outdated files are ignored:
load()returnsnullandremember()rebuilds.
Lower-level methods: load($router), write($router->getRoutes()),
exists(), clear().
Development
composer install
composer check # PHP-CS-Fixer, PHPCS (PSR-12), PHPStan level 9, Psalm level 1, PHPUnit
License
MIT. See LICENSE.