How to Create a custom Route Loader

How to Create a custom Route Loader

Basic applications can define all their routes in a single configuration file - usually config/routes.yaml (see Creating Routes). However, in most applications it’s common to import routes definitions from different resources: PHP annotations in controller files, YAML, XML or PHP files stored in some directory, etc.

Built-in Route Loaders

Symfony provides several route loaders for the most common needs:

  • YAML

    1. # config/routes.yaml
    2. app_file:
    3. # loads routes from the given routing file stored in some bundle
    4. resource: '@AcmeBundle/Resources/config/routing.yaml'
    5. app_annotations:
    6. # loads routes from the PHP annotations of the controllers found in that directory
    7. resource: '../src/Controller/'
    8. type: annotation
    9. app_directory:
    10. # loads routes from the YAML, XML or PHP files found in that directory
    11. resource: '../legacy/routing/'
    12. type: directory
    13. app_bundle:
    14. # loads routes from the YAML, XML or PHP files found in some bundle directory
    15. resource: '@AcmeOtherBundle/Resources/config/routing/'
    16. type: directory
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <!-- loads routes from the given routing file stored in some bundle -->
    8. <import resource="@AcmeBundle/Resources/config/routing.yaml"/>
    9. <!-- loads routes from the PHP annotations of the controllers found in that directory -->
    10. <import resource="../src/Controller/" type="annotation"/>
    11. <!-- loads routes from the YAML or XML files found in that directory -->
    12. <import resource="../legacy/routing/" type="directory"/>
    13. <!-- loads routes from the YAML or XML files found in some bundle directory -->
    14. <import resource="@AcmeOtherBundle/Resources/config/routing/" type="directory"/>
    15. </routes>
  • PHP

    1. // config/routes.php
    2. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    3. return function (RoutingConfigurator $routes) {
    4. // loads routes from the given routing file stored in some bundle
    5. $routes->import('@AcmeBundle/Resources/config/routing.yaml');
    6. // loads routes from the PHP annotations of the controllers found in that directory
    7. $routes->import('../src/Controller/', 'annotation');
    8. // loads routes from the YAML or XML files found in that directory
    9. $routes->import('../legacy/routing/', 'directory');
    10. // loads routes from the YAML or XML files found in some bundle directory
    11. $routes->import('@AcmeOtherBundle/Resources/config/routing/', 'directory');
    12. };

Note

When importing resources, the key (e.g. app_file) is the name of collection. Just be sure that it’s unique per file so no other lines override it.

If your application needs are different, you can create your own custom route loader as explained in the next section.

What is a Custom Route Loader

A custom route loader enables you to generate routes based on some conventions, patterns or integrations. An example for this use-case is the OpenAPI-Symfony-Routing library where routes are generated based on OpenAPI/Swagger annotations. Another example is the SonataAdminBundle that creates routes based on CRUD conventions.

Loading Routes

The routes in a Symfony application are loaded by the Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader. This loader uses several other loaders (delegates) to load resources of different types, for instance YAML files or @Route annotations in controller files. The specialized loaders implement Symfony\Component\Config\Loader\LoaderInterface and therefore have two important methods: [supports()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/LoaderInterface.php "Symfony\Component\Config\Loader\LoaderInterface::supports()") and [load()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/LoaderInterface.php "Symfony\Component\Config\Loader\LoaderInterface::load()").

Take these lines from the routes.yaml:

  • YAML

    1. # config/routes.yaml
    2. controllers:
    3. resource: ../src/Controller/
    4. type: annotation
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <import resource="../src/Controller" type="annotation"/>
    8. </routes>
  • PHP

    1. // config/routes.php
    2. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    3. return function (RoutingConfigurator $routes) {
    4. $routes->import('../src/Controller', 'annotation');
    5. };

When the main loader parses this, it tries all registered delegate loaders and calls their [supports()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/LoaderInterface.php "Symfony\Component\Config\Loader\LoaderInterface::supports()") method with the given resource (../src/Controller/) and type (annotation) as arguments. When one of the loader returns true, its [load()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/LoaderInterface.php "Symfony\Component\Config\Loader\LoaderInterface::load()") method will be called, which should return a Symfony\Component\Routing\RouteCollection containing Symfony\Component\Routing\Route objects.

Note

Routes loaded this way will be cached by the Router the same way as when they are defined in one of the default formats (e.g. XML, YAML, PHP file).

Loading Routes with a Custom Service

Using a regular Symfony service is the simplest way to load routes in a customized way. It’s much easier than creating a full custom route loader, so you should always consider this option first.

To do so, define type: service as the type of the loaded routing resource and configure the service and method to call:

  • YAML

    1. # config/routes.yaml
    2. admin_routes:
    3. resource: 'admin_route_loader::loadRoutes'
    4. type: service
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <import resource="admin_route_loader::loadRoutes" type="service"/>
    8. </routes>
  • PHP

    1. // config/routes.php
    2. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    3. return function (RoutingConfigurator $routes) {
    4. $routes->import('admin_route_loader::loadRoutes', 'service');
    5. };

In this example, the routes are loaded by calling the loadRoutes() method of the service whose ID is admin_route_loader. Your service doesn’t have to extend or implement any special class, but the called method must return a Symfony\Component\Routing\RouteCollection object.

If you’re using autoconfigure, your class should implement the Symfony\Bundle\FrameworkBundle\Routing\RouteLoaderInterface interface to be tagged automatically. If you’re not using autoconfigure, tag it manually with routing.route_loader.

Deprecated since version 4.4: Not tagging or implementing your route loader was deprecated in Symfony 4.4.

Note

The routes defined using service route loaders will be automatically cached by the framework. So whenever your service should load new routes, don’t forget to clear the cache.

Tip

If your service is invokable, you don’t need to precise the method to use.

New in version 4.3: The support of the __invoke() method to create invokable service route loaders was introduced in Symfony 4.3.

Creating a custom Loader

To load routes from some custom source (i.e. from something other than annotations, YAML or XML files), you need to create a custom route loader. This loader has to implement Symfony\Component\Config\Loader\LoaderInterface.

In most cases it is easier to extend from Symfony\Component\Config\Loader\Loader instead of implementing Symfony\Component\Config\Loader\LoaderInterface yourself.

The sample loader below supports loading routing resources with a type of extra. The type name should not clash with other loaders that might support the same type of resource. Make up any name specific to what you do. The resource name itself is not actually used in the example:

  1. // src/Routing/ExtraLoader.php
  2. namespace App\Routing;
  3. use Symfony\Component\Config\Loader\Loader;
  4. use Symfony\Component\Routing\Route;
  5. use Symfony\Component\Routing\RouteCollection;
  6. class ExtraLoader extends Loader
  7. {
  8. private $isLoaded = false;
  9. public function load($resource, $type = null)
  10. {
  11. if (true === $this->isLoaded) {
  12. throw new \RuntimeException('Do not add the "extra" loader twice');
  13. }
  14. $routes = new RouteCollection();
  15. // prepare a new route
  16. $path = '/extra/{parameter}';
  17. $defaults = [
  18. '_controller' => 'App\Controller\ExtraController::extra',
  19. ];
  20. $requirements = [
  21. 'parameter' => '\d+',
  22. ];
  23. $route = new Route($path, $defaults, $requirements);
  24. // add the new route to the route collection
  25. $routeName = 'extraRoute';
  26. $routes->add($routeName, $route);
  27. $this->isLoaded = true;
  28. return $routes;
  29. }
  30. public function supports($resource, $type = null)
  31. {
  32. return 'extra' === $type;
  33. }
  34. }

Make sure the controller you specify really exists. In this case you have to create an extra() method in the ExtraController:

  1. // src/Controller/ExtraController.php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. class ExtraController extends AbstractController
  6. {
  7. public function extra($parameter)
  8. {
  9. return new Response($parameter);
  10. }
  11. }

Now define a service for the ExtraLoader:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Routing\ExtraLoader:
    5. tags: [routing.loader]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- ... -->
    9. <service id="App\Routing\ExtraLoader">
    10. <tag name="routing.loader"/>
    11. </service>
    12. </services>
    13. </container>
  • PHP

    1. // config/services.php
    2. use App\Routing\ExtraLoader;
    3. $container->autowire(ExtraLoader::class)
    4. ->addTag('routing.loader')
    5. ;

Notice the tag routing.loader. All services with this tag will be marked as potential route loaders and added as specialized route loaders to the routing.loader service, which is an instance of Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader.

Using the Custom Loader

If you did nothing else, your custom routing loader would not be called. What remains to do is adding a few lines to the routing configuration:

  • YAML

    1. # config/routes.yaml
    2. app_extra:
    3. resource: .
    4. type: extra
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <import resource="." type="extra"/>
    8. </routes>
  • PHP

    1. // config/routes.php
    2. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    3. return function (RoutingConfigurator $routes) {
    4. $routes->import('.', 'extra');
    5. };

The important part here is the type key. Its value should be extra as this is the type which the ExtraLoader supports and this will make sure its load() method gets called. The resource key is insignificant for the ExtraLoader, so it is set to . (a single dot).

Note

The routes defined using custom route loaders will be automatically cached by the framework. So whenever you change something in the loader class itself, don’t forget to clear the cache.

More Advanced Loaders

If your custom route loader extends from Symfony\Component\Config\Loader\Loader as shown above, you can also make use of the provided resolver, an instance of Symfony\Component\Config\Loader\LoaderResolver, to load secondary routing resources.

You still need to implement [supports()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/LoaderInterface.php "Symfony\Component\Config\Loader\LoaderInterface::supports()") and [load()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/LoaderInterface.php "Symfony\Component\Config\Loader\LoaderInterface::load()"). Whenever you want to load another resource - for instance a YAML routing configuration file - you can call the [import()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Config/Loader/Loader.php "Symfony\Component\Config\Loader\Loader::import()") method:

  1. // src/Routing/AdvancedLoader.php
  2. namespace App\Routing;
  3. use Symfony\Component\Config\Loader\Loader;
  4. use Symfony\Component\Routing\RouteCollection;
  5. class AdvancedLoader extends Loader
  6. {
  7. public function load($resource, $type = null)
  8. {
  9. $routes = new RouteCollection();
  10. $resource = '@ThirdPartyBundle/Resources/config/routes.yaml';
  11. $type = 'yaml';
  12. $importedRoutes = $this->import($resource, $type);
  13. $routes->addCollection($importedRoutes);
  14. return $routes;
  15. }
  16. public function supports($resource, $type = null)
  17. {
  18. return 'advanced_extra' === $type;
  19. }
  20. }

Note

The resource name and type of the imported routing configuration can be anything that would normally be supported by the routing configuration loader (YAML, XML, PHP, annotation, etc.).

Note

For more advanced uses, check out the ChainRouter provided by the Symfony CMF project. This router allows applications to use two or more routers combined, for example to keep using the default Symfony routing system when writing a custom router.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.