Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing Symfony routes with complicated/many params

I often find myself with routes that require 2+ (sometimes 4+) parameters to generate a route. This is fine as long as I only need to generate the route in a couple spots. But I often find myself reproducing the list of parameters in many locations, both in Twig and PHP (Controllers and Services). The parameters are often something more than the record ID.

For example, say I have the following route:

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

To generate this in Twig I need to 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 1 place, but awful once you start coping it everywhere and even worse when someone decides they don't want to include the ID any more.

Question: Is there a way to add a reusable method, say product_path($product) that can be used both in Twig and Controllers/Services? Or extend Router or UrlGenerator to determine how an entity/object should be used for route generation?

I can make a service to do it and then a Twig extension, but seems like a common thing to do and a lot of work/code to accomplish.

One idea is where I could something like:

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

From there it could figure out how to generate the URL. Of course the logic would be something I wrote, but I'd only need to pass the router around.

like image 212
Darryl Hein Avatar asked Nov 08 '22 12:11

Darryl Hein


1 Answers

I think the simplest solution is to create a custom service and twig extension like you said with your own twig function.

After some little investigation, The path twig function use the UrlGenerator class and it seems more difficult to override it properly than to create a custom service/twig function.

like image 92
Fabien Salles Avatar answered Nov 15 '22 11:11

Fabien Salles