Dynamically change Symfony2 router file

I have a website using Symfony2 and I would like to have a completely different routing file depending on the user (ip address, ...)

My first idea was to load a different environment, if the user function, but the kernel (so the environment setting) is set before events, I think this solution will not work.

I want to keep the same url, not redirect to another site ...

If you have any ideas, thanks :)

+3


source to share


2 answers


You can create an additional loader that will extend the existing loaders, for example in the documentation . In your case:

<?php


namespace AppBundle\Routing;

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

class AdvancedLoader extends Loader
{
    private $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

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

        $ip = $this->request->getClientIp();

        if($ip == '127.0.0.1'){
            $resource = '@AppBundle/Resources/config/import_routing1.yml';
        }else{
            $resource = '@AppBundle/Resources/config/import_routing2.yml';
        }

        $type = 'yaml';

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

        $collection->addCollection($importedRoutes);

        return $collection;
    }

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

      


AppBundle / Resources / config / services.yml



services:
   app.routing_loader:
       class: AppBundle\Routing\AdvancedLoader
       arguments: [@request=]
       tags:
           - { name: routing.loader }

      


app / config / routing.yml

app_advanced:
    resource: .
    type: advanced_extra

      

+4


source


You can use a PHP file as your main router and then depending on your conditions (user, IP, ...) you can load dynamic routes or load separate routing files.

Going to http://symfony.com/doc/current/book/routing.html allows you to set up your routing like this:



# app/config/config.yml
framework:
    # ...
    router: { resource: "%kernel.root_dir%/config/routing.php" }

      

In the routing.php file you can import static files (yml, xml) or just register routes directly there (it all depends on your specific conditions).

0


source







All Articles