Custom Route Loader in Symfony 2

November 23, 2015 | No Comments | Programming | PHP Routing Loader Service Symfony2

Sometimes we want to load different routing file depends on user data or environment variables. Symfony has article in cookbook which explains such functionality but I can share with you how to create Custom Route Loader in Symfony2 with some nuances/pitfalls and working example.

For example, you have a task to load routing depends on current date. Lets imagine that we have default AppBundle with default directory structure and yaml configuration in Resource folder. Then we need to create DateLoader.php file:

<?php
 
namespace AppBundle\Routing;
 
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;
 
class DateLoader extends Loader
{
    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();
 
        if(date('Y') == 2015){
            $resource = '@AppBundle/Resources/config/routing_2015.yml';
        }else{
            $resource = '@AppBundle/Resources/config/routing_another.yml';
        }
 
        $type = 'yaml';
 
        $importedRoutes = $this->import($resource, $type);
 
        $collection->addCollection($importedRoutes);
 
        return $collection;
    }
 
    public function supports($resource, $type = null)
    {
        return 'date_extra' === $type;
    }
}

This is simple service which loading routing depends on current date. Supports type name is not important here.

Now you need to register this service in Service Container (AppBundle/Resources/config/services.yml):

services:
   app.routing_date_loader:
       class: AppBundle\Routing\DateLoader
       tags:
           - { name: routing.loader }

The key here is tag routing.loader which will assign this service with routing loader. More information about tags you can find in official documentation:

Last, you should place your custom loader type in your routing file app/config/routing.yml:

date_extra:
    resource: .
    type: date_extra

Thats, all but it has common pitfall here – cache. You can disable it in app/config/parameters.yml:

parameters:
    router.options.matcher.cache_class: ~

Now your routing should load routes file dynamically depends on your parameters. You can also inject variables into your service and create more complex conditions for your Route Loader but don’t forget about performance and optimization here.


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT