Many modern PHP frameworks support attribute routing, which allows you to define routes directly in your controller methods using PHP 8 attributes.
use App\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class ProductController extends AbstractController
{
#[Route('/products', name: 'product_list', methods: ['GET'])]
public function list(): Response
{
// Logic to list products
}
#[Route('/products/{id}', name: 'product_show', methods: ['GET'])]
public function show(int $id): Response
{
// Logic to show a specific product
}
}
This example uses Symfony's routing attributes, but similar concepts exist in other frameworks. Attribute routing can make your code more readable and maintainable by keeping route definitions close to the controller actions they correspond to.