Revision: Fri, 17 May 2024 13:03:36 GMT
v2.14 – outdated
This version of the documentation is outdated. Consider upgrading your project to Spiral Framework 3.12
Edit this page

HTTP - Annotated Routing

Use spiral/annotated-routes extension to declare application routes using attributes or annotations.

To install the extension:

composer require spiral/annotated-routes

Please note that the spiral/framework >= 2.6 already includes this component.

Activate the bootloader Spiral\Router\Bootloader\AnnotatedRoutesBootloader in your application (you can disable the default RoutesBootloader):

protected const LOAD = [

You can use the extension.

Define the route

To define the route, make sure to use Spiral\Router\Annotation\Route:

namespace App\Controller;

use Spiral\Router\Annotation\Route;

class HomeController
    #[Route(route: '/', name: 'index', methods: 'GET')] 
    public function index(): string
        return 'hello world';

Following route attributes are available:

Attribute Type Description
route string Route patterns, follow the same rules as the default Router. Required.
name string Route name. Optional.
methods array/string HTTP methods. Defaults to all methods.
defaults array Default values for route pattern.
group string Route group, defaults to default.
middleware array Route specific middleware class names.
priority int (Available since v2.9). Position in a routes list. Higher priority routes are sorted before lower ones. Helps to solve situations when one request matches two routes. Defaults to 0.

If you won't define a route name it will be generated automatically. For example, #Route(route: '/api/news', methods: ["POST", "PATCH"]) will generate post,patch:/api/news

Route Groups

It is possible to apply shared rules, middleware, domain core, or prefix to the group of routes. Create and register bootloader to achieve that:

namespace App\Bootloader;

use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Router\GroupRegistry;

class APIRoutes extends Bootloader
    public function boot(GroupRegistry $groups): void

Make sure to register bootloader after AnnotatedRoutesBootloader. Use the default group to configure all the routes.

You can now assign the route to the group using the group attribute.

#[Route(route: '/', name: 'index', methods: 'GET', group: 'api')]  
public function index(): ResponseInterface
    // ...    

Route middleware, prefix, and domain core will be added automatically.

Route Cache

By default, all the annotated routes cached when DEBUG is off. To turn on/off route-cache separately from DEBUG env variable set the ROUTE_CACHE env variable:


Run the route:reset to reset the route cache:

php app.php route:reset