debuss-a/fastroute-attribute-loader

An attribute route loader for FastRoute.

Installs: 1

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/debuss-a/fastroute-attribute-loader

1.0.0 2026-01-31 21:55 UTC

This package is auto-updated.

Last update: 2026-01-31 21:56:47 UTC


README

A simple and elegant route loader for nikic/fast-route that uses PHP 8 attributes to define routes directly on your controller methods.

Installation

Install via Composer:

composer require debuss-a/fastroute-attribute-loader

Requirements

  • PHP 8.2 or higher
  • nikic/fast-route ^1.0

Usage

1. Define Routes with Attributes

Use the #[Route] attribute on your controller methods:

<?php

namespace App\Controller;

use FastRoute\Attribute\Route;
use Psr\Http\Message\{ResponseInterface,ServerRequestInterface};
use Psr\Http\Server\RequestHandlerInterface;

class UserController implements RequestHandlerInterface
{

    #[Route('/users[/{id:\d+}]', methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])]
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute('id');
        $method = $request->getMethod();
        $body = $request->getParsedBody();
        
        // Handle the request based on $method and $id
        return match ($method) {
            'GET' => $this->getUser($id),
            'POST' => $this->createUser($body),
            'PUT', 'PATCH' => $this->updateUser($id, $body),
            'DELETE' => $this->deleteAlbum($id),
        };
    }
    
    public function getUser(?int $id = null): ResponseInterface
    {
        // List all users or return a specific user if $id is provided
    }

    public function createUser(array $body): ResponseInterface
    {
        // Create a new user
    }

    public function updateUser(int $id, array $body): ResponseInterface
    {
        // Update a user
    }

    public function deleteUser(int $id): ResponseInterface
    {
        // Delete a user
    }
}

2. Load Routes and Create Dispatcher

<?php

use FastRoute\Attribute\AttributeRouteLoader;
use FastRoute\RouteCollector;
use function FastRoute\simpleDispatcher;

// Create the route loader with your namespace and controllers directory
$loader = new AttributeRouteLoader(
    namespace: 'App\\Controller',
    path: __DIR__ . '/src/Controller'
);

// Create the dispatcher
$dispatcher = simpleDispatcher(function(RouteCollector $collector) use ($loader) {
    $loader->load($collector);
});

// Dispatch the request
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];

// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
    $uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);

switch ($routeInfo[0]) {
    case \FastRoute\Dispatcher::NOT_FOUND:
        // ... 404 Not Found
        break;
    case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        $allowedMethods = $routeInfo[1];
        // ... 405 Method Not Allowed
        break;
    case \FastRoute\Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        // ... call $handler with $vars
        break;
}

Route Attribute

The Route attribute accepts the following parameters:

  • path (string, required): The route pattern (supports FastRoute syntax)
  • methods (array, optional): HTTP methods (defaults to ['GET'])

Examples

// Simple GET route
#[Route('/')]

// Route with specific HTTP method
#[Route('/users', methods: ['POST'])]

// Route with multiple HTTP methods
#[Route('/users/{id:\d+}', methods: ['PUT', 'PATCH'])]

// Route with optional parameter
#[Route('/posts[/{id:\d+}]')]

// Multiple routes on the same method
#[Route('/road-one')]
#[Route('/road-two')]
public function handle(ServerRequestInterface $request): ResponseInterface
{
    // Handle both routes
}

License

MIT License. See LICENSE.md for more information.