Attribute Router
Attribute Router
The attribute router uses attributes in controller classes to define routes. This method extends the advanced router, providing a more structured and organized approach to routing.
Defining Routes
To define a route, add the #[\Hazaar\Application\Route] attribute to the controller class or method to define the actions available on this controller. Routing to the controller itself is handled by the advanced router to limit the number of controller files processed.
The attribute accepts the following parameters:
$route: The URL pattern.$method(optional): The HTTP method (GET, POST, PUT, DELETE).$responseType(optional): The expected response type.
Example:
namespace App\Controller\Api\V1;
use Hazaar\Application\Route;
class Product extends Basic {
#[Route('/list', methods: ['GET'])]
public function listProducts(): Json
{
// List products
}
#[Route('/{int:id}', methods: ['GET'])]
public function getProduct(int $id): Json
{
// Retrieve the product with the specified ID
}
}Here, the listProducts method is accessible via a GET request to /api/v1/product/list, and the getProduct method is accessible via a GET request to /api/v1/product/{id}.
Route Parameters
Define route parameters in the URL pattern using curly braces.
Example:
namespace App\Controller;
use Hazaar\Application\Route;
use Hazaar\Controller\Basic;
use Hazaar\Controller\Response\Json;
use Hazaar\DBI\Adapter;
class Product extends Basic {
#[Route('/', methods: ['GET'])]
public function listProducts(): Json
{
// List products
}
#[Route('/{int:id}', methods: ['GET'])]
public function getProduct(int $id): Json
{
$db = Adapter::create();
return new Json($db->table('product')->find(['id' => $productId]));
}
#[Route('/{int:id}', methods: ['POST'])]
public function updateProduct() {
// Update product
}
}In this example, three routes are defined on the Application\Controller\Product controller:
GETrequest to/product. This can be used to retrieve a list of products.GETrequest to/product/1234. This can be used to retrieve a single product with the ID1234.POSTrequest to/product/1234. This can be used to update a single product with the ID1234.
Configuration (app.php)
<?php
return [
'development' => [
'router' => [
'type' => 'attribute'
]
]
];For route parameters and response types, see the routing overview.