Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Cookbook
  4. Routing
  5. How to create a custom Route Loader
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Loading Routes
  • Creating a Custom Loader
    • Using the Custom Loader
  • More Advanced Loaders

How to create a custom Route Loader

Edit this page

Warning: You are browsing the documentation for Symfony 2.1, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to create a custom Route Loader

A custom route loader allows you to add routes to an application without including them, for example, in a Yaml file. This comes in handy when you have a bundle but don't want to manually add the routes for the bundle to app/config/routing.yml. This may be especially important when you want to make the bundle reusable, or when you have open-sourced it as this would slow down the installation process and make it error-prone.

Alternatively, you could also use a custom route loader when you want your routes to be automatically generated or located based on some convention or pattern. One example is the FOSRestBundle where routing is generated based off the names of the action methods in a controller.

Note

There are many bundles out there that use their own route loaders to accomplish cases like those described above, for instance FOSRestBundle, KnpRadBundle and SonataAdminBundle.

Loading Routes

The routes in a Symfony application are loaded by the DelegatingLoader. This loader uses several other loaders (delegates) to load resources of different types, for instance Yaml files or @Route and @Method annotations in controller files. The specialized loaders implement LoaderInterface and therefore have two important methods: supports() and load().

Take these lines from routing.yml:

1
2
3
4
_demo:
    resource: "@AcmeDemoBundle/Controller/DemoController.php"
    type:     annotation
    prefix:   /demo

When the main loader parses this, it tries all the delegate loaders and calls their supports() method with the given resource (@AcmeDemoBundle/Controller/DemoController.php) and type (annotation) as arguments. When one of the loader returns true, its load() method will be called, which should return a RouteCollection containing Route objects.

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 should implement LoaderInterface.

The sample loader below supports loading routing resources with a type of extra. The type extra isn't important - you can just invent any resource type you want. The resource name itself is not actually used in the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
namespace Acme\DemoBundle\Routing;

use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExtraLoader implements LoaderInterface
{
    private $loaded = false;

    public function load($resource, $type = null)
    {
        if (true === $this->loaded) {
            throw new \RuntimeException('Do not add the "extra" loader twice');
        }

        $routes = new RouteCollection();

        // prepare a new route
        $pattern = '/extra/{parameter}';
        $defaults = array(
            '_controller' => 'AcmeDemoBundle:Demo:extra',
        );
        $requirements = array(
            'parameter' => '\d+',
        );
        $route = new Route($pattern, $defaults, $requirements);

        // add the new route to the route collection:
        $routeName = 'extraRoute';
        $routes->add($routeName, $route);

        return $routes;
    }

    public function supports($resource, $type = null)
    {
        return 'extra' === $type;
    }

    public function getResolver()
    {
        // needed, but can be blank, unless you want to load other resources
        // and if you do, using the Loader base class is easier (see below)
    }

    public function setResolver(LoaderResolverInterface $resolver)
    {
        // same as above
    }
}

Note

Make sure the controller you specify really exists.

Now define a service for the ExtraLoader:

  • YAML
  • XML
  • PHP
1
2
3
4
5
services:
    acme_demo.routing_loader:
        class: Acme\DemoBundle\Routing\ExtraLoader
        tags:
            - { name: routing.loader }
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="acme_demo.routing_loader" class="Acme\DemoBundle\Routing\ExtraLoader">
            <tag name="routing.loader" />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
use Symfony\Component\DependencyInjection\Definition;

$container
    ->setDefinition(
        'acme_demo.routing_loader',
        new Definition('Acme\DemoBundle\Routing\ExtraLoader')
    )
    ->addTag('routing.loader')
;

Notice the tag routing.loader. All services with this tag will be marked as potential route loaders and added as specialized routers to the DelegatingLoader.

Using the Custom Loader

If you did nothing else, your custom routing loader would not be called. Instead, you only need to add a few extra lines to the routing configuration:

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

    <import resource="." type="extra" />
</routes>
1
2
3
4
5
6
7
// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;

$collection = new RouteCollection();
$collection->addCollection($loader->import('.', 'extra'));

return $collection;

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

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

In most cases it's better not to implement LoaderInterface yourself, but extend from Loader. This class knows how to use a LoaderResolver to load secondary routing resources.

Of course you still need to implement supports() and load(). Whenever you want to load another resource - for instance a Yaml routing configuration file - you can call the import() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace Acme\DemoBundle\Routing;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;

class AdvancedLoader extends Loader
{
    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();

        $resource = '@AcmeDemoBundle/Resources/config/import_routing.yml';
        $type = 'yaml';

        $importedRoutes = $this->import($resource, $type);

        $collection->addCollection($importedRoutes);

        return $collection;
    }

    public function supports($resource, $type = null)
    {
        return $type === 'advanced_extra';
    }
}

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.).

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Take the exam at home

    Take the exam at home

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of ismail BASKIN, a Symfony contributor

    Thanks ismail BASKIN for being a Symfony contributor

    1 commit • 2 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia