在 symfony 1.4 中,您可以定义自定义路由类,在其中使用自定义逻辑覆盖 url 的生成,例如:
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)。
你如何处理这个 symfony2 ?
我可以想到两种方法。第一个也是最简单的方法是用您自己的类扩展 Router 类,并告诉 symfony 在您的parameters.yml 或 config.yml 中使用您的类:
parameters:
router.class: Company\CoreBundle\Routing\MyCustomRouter
有一个更强大(读:复杂)的解决方案,它允许您通过覆盖或扩展整个路由器来定义对路由器类的更多依赖项service。有一个包可以做到这一点,称为BeSimpleI18n路由包 https://github.com/BeSimple/BeSimpleI18nRoutingBundle您可以查看它是如何完成的。
具体来说,请注意编译器通行证 https://github.com/BeSimple/BeSimpleI18nRoutingBundle/blob/master/DependencyInjection/Compiler/OverrideRoutingCompilerPass.php他们替换默认值的地方router
服务有自己的。然后你必须实施路由器接口 http://api.symfony.com/2.0/Symfony/Component/Routing/RouterInterface.html在你自己的路由器类中。在这个特定的捆绑包中,他们注入原来的默认路由器 https://github.com/BeSimple/BeSimpleI18nRoutingBundle/blob/master/Resources/config/routing.xml#L16(在编译器通道中重命名它之后)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)