![Stop writing the same regex for #[Route]](/_next/image?url=https%3A%2F%2Fmedia2.dev.to%2Fdynamic%2Fimage%2Fwidth%3D1000%2Cheight%3D500%2Cfit%3Dcover%2Cgravity%3Dauto%2Cformat%3Dauto%2Fhttps%253A%252F%252Fdev-to-uploads.s3.amazonaws.com%252Fuploads%252Farticles%252Fbp1axjdtq95xsw98ubq1.png&w=1200&q=75)
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 { // ... } 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
Continue reading on Dev.to Webdev
Opens in a new tab

