How to override Router URL Generator in Symfony 5
Let’s say you make multitenant SaaS system using Symfony 5 and you have tenant ID in every route. You don’t want to add it on every `path()` call, you want to have it added automatically.
What you need to do? Override default Symfony Router! And here is how to do it:
For this specific scenario Service Decorators come handy. In services.yaml you define your own service letting DI know that you want to override router:
After that we only need to implement our own router:
You can see generate method with updated implementation. Remember: this change will affect every route generated — even internal _profiler and _wdt so (as shown in code) you must exclude them from any updates. Best idea would be have a list of routes you want to interfere with.
Good luck!