Is it possible to add custom routes during compilation?

I am preparing an external package, and I would like to add several routes during compilation. Routes will be created in the main settings app/config/config.yml .

I tried to get router from ContainerBuilder in my CustomCompilerPass with:

 $definition = $container->getDefinition('router'); 

but I got The service definition "router" does not exist .

Is it possible to add custom routes during compilation?

+4
source share
2 answers

Unable to add routes to compiler passes.
To dynamically load routes (knowing the parameters of the container), I used a custom route loader , as indicated in my previous example

 class MyLoader extends Loader { protected $params; public function __construct($params) { $this->params = $params; } public function supports($resource, $type = null) { return $type === 'custom' && $this->params == 'YourLogic'; } public function load($resource, $type = null) { // This method will only be called if it suits the parameters $routes = new RouteCollection; $resource = '@AcmeFooBundle/Resources/config/dynamic_routing.yml'; $type = 'yaml'; $routes->addCollection($this->import($resource, $type)); return $routes; } } 

routing.yml

 _custom_routes: resource: . type: custom 
+2
source

router is an alias, not a service. To get this from ContainerBuilder , use ContainerBuilder::getAlias . To get the service identifier, you need to pass this object to the string: (string) $container->getAlias('router') . Now you can use this identifier to get the service: $container->getDefinition($container->getAlias('router')) . And then you get a Service that you can change to add routes.


By the way, I'm not sure if this is really what you want. How about using a CmfRoutingBundle . Then you use the Chain Router, so you can use both the Symfony2 router and DynamicRouter. DynamicRouter can be used with a custom route provider, in which you return the necessary routes (you can get them from any resource you need).

0
source

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


All Articles