Symfony 2 自定义路由 [英] Custom routing with Symfony 2

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

问题描述

我有一些相当复杂的路由规则,这些规则只能通过自定义代码实现,而不能通过默认路由器实现.

I have some fairly complex routing rules, that are only achievable with custom code, and not with the default router.

路由器也要考虑域名.

是否有可能(以及如何)定义我自己的 Router 类,该类将有一个方法接受 Request 并返回包/控制器名称?

Is it possible (and how) to define my own Router class, that would have a method accepting a Request and returning the bundle/controller name?

推荐答案

要实现您的要求,您无需完全重新定义路由器

To achieve what you're asking, you don't need to completely redefine the router

您可以简单地编写自己的类来实现 UrlMatcherInterface.如果您也希望能够生成与您的方案匹配的 URL,则必须创建另一个覆盖 UrlGeneratorInterface 也是如此.

You can simply write your own class that implements UrlMatcherInterface. If you want to be able to generate URLs that match your scheme as well, you'll have to create another class which overrides UrlGeneratorInterface as well.

为了考虑域名,您需要使用RequestContext,它被传递给他们的构造函数(它没有很好的文档记录,但请检查Router::get{Matcher,Generator} 了解详情.

In order to take into account the domain name, you'll need to use RequestContext, which is passed to their constructors (it's not well documented, but check Router::get{Matcher,Generator} for the details).

一旦你的类准备好,你可以通过覆盖包中的参数router.options.generator_class"和router.options.matcher_class"将它们注入到路由器中.

Once your classes are prepared, you can inject them into the router simply by overriding the parameters "router.options.generator_class" and "router.options.matcher_class" in your bundle.

但是,这可能不是您想要的最佳方法 - 像这样覆盖路由器的部分需要非常小心以保留所有缓存.

However, it may not be the best approach for what you want - overriding parts of the router like that requires a lot of care to preserve all of the caching.

您可能想考虑使用 Symfony2 的普通路由器,但根据请求的域是什么来处理不同的路由文件.如果您将 Web 服务器配置为根据域名设置变量或执行不同的前端控制器,则可以轻松完成此操作.

You might want to consider using Symfony2's normal router, but handing it different route files depending on what the request's domain is. This can be done easily if you configure your web server to set a variable or execute a different front controller depending on the domain name.

使用该信息,您可以为每个请求加载不同的环境",不同环境之间的唯一区别是它们使用不同的路由文件.

Using that information, you can then load a different 'environment' per-request, with the only difference between the different environments being that they use different routing files.

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

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