Dziamid
Dziamid

Reputation: 11581

Custom route class

In symfony 1.4 you could define a custom route class, where you override the generation of url with custom logic, for example:

custom:
  class: sfDoctrineRouteCollection
  options:
    model:                Custom
    prefix_path:          /custom/category/:category_id
    column:               id
    route_class:          CustomDoctrineRoute

class CustomDoctrineRoute extends sfDoctrineRoute
{
  public function generate($params, $context = array(), $absolute = false)
  {
    if (!isset($params['category_id'])) {
      $params['category_id'] = sfContext::getInstance()->getRequest()->getParameter('category_id');
    }

    return parent::generate($params, $context, $absolute);
  }

}

This allows to write url_for('custom_show', array('id'=> $object['id'])) and not bother about context dependent parameters (category_id).

How do you approach this is symfony2?

Upvotes: 5

Views: 962

Answers (1)

MDrollette
MDrollette

Reputation: 6927

I can think of 2 approaches to this. The first, and simplest, is to extend the Router class with your own and tell symfony to use your class in your parameters.yml or config.yml:

parameters:
    router.class: Company\CoreBundle\Routing\MyCustomRouter

There's a more powerful (read: complicated) solution which allows you to define more dependencies on your router class by overriding or extending the whole router service. There is a bundle that does this called BeSimpleI18nRoutingBundle which you can look at to see how it's done.

Specifically, notice the CompilerPass where they replace the default router service with their own. You then have to implement the RouterInterface in your own router class. In this particular bundle they inject the original default router (after having renamed it in the compiler pass).

Upvotes: 3

Related Questions