DEV Community

Cover image for Stop writing the same regex for #[Route]
Stiven Llupa
Stiven Llupa

Posted on

Stop writing the same regex for #[Route]

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
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

You write:

#[Route('/users/{id}', requirements: [
    'id' => Requirement::UUID,
])]
public function show(string $id): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Instead of:

#[Route('/blog/{slug}', requirements: [
    'slug' => '[a-z0-9]+(?:-[a-z0-9]+)*',
])]
public function post(string $slug): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

You write:

#[Route('/blog/{slug}', requirements: [
    'slug' => Requirement::ASCII_SLUG,
])]
public function post(string $slug): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

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.

Watch it on YouTube

Top comments (0)