Reusing Symfony routes with complex / many options

I often come across routes that require 2+ (sometimes 4+) parameters to create a route. This is normal, so far I only need to generate a route in a couple of spots. But I often find that I reproduce a list of parameters in many places, both in Twig and in PHP (controllers and services). Parameters are often more than a record identifier.

For example, let's say I have the following route:

/product/{id}/{category_slug}/{category_sub_slug}/{product_slug} 

To generate this in Twig, I need something like:

 path('product_view', { id: product.id, category_slug: product.subCategory.category.slug, category_sub_slug: product.subCategory.slug, product_slug: product.slug }) 

This is bad enough in 1st place, but terrible when you start dealing with it everywhere and even worse when someone decides that they no longer want to include the identifier.

Question: Is there a way to add a reuse method, say product_path($product) , which can be used in both Twig and Controllers / Services? Or expand a router or UrlGenerator to determine how an object / object should be used to generate a route?

I can do a service to do this and then a Twig extension, but it seems like this is a normal thing and a lot of work / code to execute.

One idea is where I could be something like:

 path('product_view', { product: product }) $this->generateUrl('product_view', ['product': product]); 

From there, he can figure out how to create the URL. Of course, the logic would be what I wrote, but I only needed to skip the router.

+5
source share
1 answer

I think the easiest solution is to create a custom service and expand the branch, as you said using your own twig function.

After a little investigation, the path twig function uses the UrlGenerator class , and it seems harder to override it correctly than creating a custom service / twig function.

+1
source

Source: https://habr.com/ru/post/1274487/


All Articles