自定义路由类 [英] Custom route class

查看:49
本文介绍了自定义路由类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 symfony 1.4 中,您可以定义自定义路由类,您可以在其中使用自定义逻辑覆盖 url 的生成,例如:

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);
  }

}

这允许编写 url_for('custom_show', array('id'=> $object['id'])) 而不必担心上下文相关参数(category_id).

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

你如何看待 symfony2?

How do you approach this is symfony2?

推荐答案

我可以想到 2 种方法来解决这个问题.第一个,也是最简单的,是用你自己的扩展 Router 类,并告诉 symfony 在你的 parameters.yml 或 config.yml 中使用你的类:

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

有一个更强大(阅读:复杂)的解决方案,它允许您通过覆盖或扩展整个路由器服务来定义对路由器类的更多依赖.有一个名为 BeSimpleI18nRoutingBundle 的包可以执行此操作,您可以查看它是如何完成的.

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.

具体来说,请注意 CompilerPass 替换的位置默认的 router 服务带有自己的.然后你必须在你自己的路由器类中实现 RouterInterface.在这个特定的包中,他们注入原始默认路由器 (在编译器阶段重命名后).

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

这篇关于自定义路由类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆