Skip to content
Antares

Route Attributes

Routes are defined by placing attributes on controller methods. The router discovers them via reflection when you call $router->register(ControllerClass::class).

use Antares\Router\Attributes\Get;
use Antares\Router\Attributes\Post;
use Antares\Router\Attributes\Put;
use Antares\Router\Attributes\Patch;
use Antares\Router\Attributes\Delete;
class UserController
{
#[Get('/users')]
public function index(): array { /* ... */ }
#[Get('/users/{id}')]
public function show(int $id): array { /* ... */ }
#[Post('/users', 201)]
public function store(CreateUserRequest $request): UserResponse { /* ... */ }
#[Put('/users/{id}')]
public function update(int $id, UpdateUserRequest $request): UserResponse { /* ... */ }
#[Patch('/users/{id}')]
public function patch(int $id, PatchUserRequest $request): UserResponse { /* ... */ }
#[Delete('/users/{id}', 204)]
public function destroy(int $id): void { /* ... */ }
}

The second argument to any route attribute sets the success status code. Each attribute has its own default:

AttributeDefault status
#[Get]200
#[Post]201
#[Put]200
#[Patch]200
#[Delete]204

Pass the status explicitly when the default doesn’t fit, for example a login or search endpoint that uses POST but doesn’t create anything: #[Post('/auth/login', 200)].

#[Post('/users', 201)]
public function store(): UserResponse { /* ... */ }
#[Delete('/users/{id}', 204)]
public function destroy(int $id): void { /* ... */ }

Segments wrapped in {} are route parameters:

#[Get('/posts/{postId}/comments/{commentId}')]
public function show(int $postId, int $commentId): array { /* ... */ }

Because the router is built on nikic/fast-route, you can also restrict a parameter with a regex: #[Get('/users/{id:\d+}')].

$router->match() returns the parameters as strings, keyed by name. In the framework, the Dispatcher passes them to the method argument with the same name and casts them to int, float or bool. A value that doesn’t fit the type (for example /users/abc for int $id) is rejected with 400 Bad Request.

[$controller, $method, $params, $status] = $router->match('GET', '/posts/7/comments/3');
// CommentController::class, 'show', ['postId' => '7', 'commentId' => '3'], 200
$router = new Router();
$router->register(UserController::class);
$router->register(PostController::class);

register() scans every method of the class. A method can carry several route attributes for different HTTP methods, for example both #[Put] and #[Patch].