Did you know Symfony ships with a built-in class full of pre-defined route requirement patterns?
It's called Requirement, and it lives in Symfony\Component\Routing\Requirement.
Instead of writing your own regex for common route parameters like UUIDs, slugs, date formats, or locale codes, you can just reference a constant.
So instead of this mess in your route attribute:
#[Route('/users/{id}', requirements: [
'id' => '[0-9a-f]{8}-[0-9a-f]{4}-'
. '[0-9a-f]{4}-[0-9a-f]{4}-'
. '[0-9a-f]{12}',
])]
public function show(string $id): Response
{
// ...
}
You write:
#[Route('/users/{id}', requirements: [
'id' => Requirement::UUID,
])]
public function show(string $id): Response
{
// ...
}
Instead of:
#[Route('/blog/{slug}', requirements: [
'slug' => '[a-z0-9]+(?:-[a-z0-9]+)*',
])]
public function post(string $slug): Response
{
// ...
}
You write:
#[Route('/blog/{slug}', requirements: [
'slug' => Requirement::ASCII_SLUG,
])]
public function post(string $slug): Response
{
// ...
}
It includes constants for all UUID formats, common date, ASCII slugs, and your usual suspects.
Stop rewriting the same regex. Symfony already did it for you.
Top comments (0)