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.