Getting the backend routing from frontend application in Symfony and vice versa

Posted on Categories:PHP, MySQL, Symfony

When using Symfony frontend application it is sometimes necessary to access other application’s routing to create an internal url that points to that application.
In order for that to be posssible, a method for getting the desired application’s routing is required.

In this example, I’m creating a getBackendRouting() method for getting the Backend application routing:

// apps/frontend/config/frontendConfiguration.class.php
...
  public function getBackendRouting()
  {
    if (!$this->backendRouting)
    {
      $this->backendRouting = new sfPatternRouting(new sfEventDispatcher());
 
      $config = new sfRoutingConfigHandler();
      $routes = $config->evaluate(array(sfConfig::get('sf_apps_dir').'/backend/config/routing.yml'));
 
      $this->backendRouting->setRoutes($routes);
    }
 
    return $this->backendRouting;
  }
...

Note that if you have defined you own routing class to use some prefix for backend applications (usually “/admin”), you should use your routing class name in frontendConfiguration.class.php:

// apps/frontend/config/frontendConfiguration.class.php
...
  public function getBackendRouting()
  {
    if (!$this->backendRouting)
    {
      $this->backendRouting = new myRoutingClass(new sfEventDispatcher(), null, array('prefix'=>'/admin'));
 
      $config = new sfRoutingConfigHandler();
      $routes = $config->evaluate(array(sfConfig::get('sf_apps_dir').'/backend/config/routing.yml'));
 
      $this->backendRouting->setRoutes($routes);
    }
 
    return $this->backendRouting;
  }
...

From now on, backend routing should be available by calling:

// Calling from action:
$this->getContext()->getConfiguration()->getActive()->getBackendRouting()->generate('my_backend_route_name');