Custom route class

吃可爱长大的小学妹 提交于 2020-01-01 10:53:55

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/8384660/custom-route-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!