简体   繁体   中英

Is it possible to add custom routes during compilation passes?

I prepare external bundle and I would like to add some routes during compilation passes. Routes will be created on the main app/config/config.yml settings.

I was trying to get router from ContainerBuilder in my CustomCompilerPass via:

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

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

Is it possible to add custom routes during compilation passes?

There's no way to add routes at compiler passes.
In order to dynamicly load routes (aware of container parameters) I'd use a custom route loader as given 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

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


BTW, I'm not sure if this is really the thing you want. What about using the CmfRoutingBundle . Then, you use the Chain Router, so you can use both the Symfony2 router and the DynamicRouter. The DynamicRouter can be used with a custom route provider, in which you return the routes you want (you can get them from every resource you want).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM