Description
Sometimes, when generating links to a resource, you need to modify the default router's behavior.
Use cases can be:
- Language switch links
- Download links
- Pass a Content item instead of a Location (and use its
mainLocationId
)
Solution
The concept of RouteReference has been introduced, which works in the same way of Symfony's ControllerReference
for sub-requests. A RouteReference
represents a route (to a location object, a declared route...) with its parameters and can be passed to the Router
for link generation.
The advantage of a RouteReference
is that its params can be modified later, and then passed to the router (e.g. to generate a link to the same location in several different languages).
Furthermore, the RouteReference
generation process can be extended to fit specific needs.
Usage
Twig
Prototype:
routing_resource
can be any valid resource (route name, Location object...). If omitted (null
), the current route will be taken into account.parameters_hash
is a hash with arbitrary key/values. It will be passed to the router in the end.
Minimal usage is pretty straightforward:
Passing parameters and play with the RouteReference:
PHP
You can easily generate links based on a RouteReference
from PHP too, with the RouteReferenceGenerator
service:
Extending the RouteReference generation process
When generating the route reference, the RouteReferenceGenerator
service fires an MVCEvents::ROUTE_REFERENCE_GENERATION
(ezpublish.routing.reference_generation) event. This event can be listened to in order to modify the final route reference (adding/changing parameters, changing the route name...).
All listeners receive a eZ\Publish\Core\MVC\Symfony\Event\RouteReferenceGenerationEvent
object, which contains the current request object and the route reference.
Service declaration:
Example