php Symfony2 中的路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4945630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:19:36  来源:igfitidea点击:

Routing in Symfony2

phproutingsymfony

提问by umpirsky

How to setup default routing in Symfony2?

如何在 Symfony2 中设置默认路由?

In Symfony1 it looked something like this:

在 Symfony1 中,它看起来像这样:

homepage:
  url:   /
  param: { module: default, action: index }

default_symfony:
  url:   /symfony/:action/...
  param: { module: default }

default_index:
  url:   /:module
  param: { action: index }

default:
  url:   /:module/:action/...

回答by Longsight

I was looking through the cookbook for an answer to this, and think I've found it here. By default, all route parameters have a hidden requirement that they match any character exceptthe / character ([^/]+), but this behaviour can be overridden with the requirements keyword, by forcing it to match anycharacter.

我正在翻阅食谱以寻找答案,我想我已经在这里找到。默认情况下,所有路由参数都有一个隐藏要求,即它们匹配/ 字符 ([^/]+)之外的任何字符,但是可以使用 requirements 关键字覆盖此行为,通过强制它匹配任何字符。

The following should create a default route that catches all others - and as such, should come last in your routing config, as any following routes will nevermatch. To ensure it matches "/" as well, a default value for the url parameter is included.

以下应该创建一个默认路由来捕获所有其他路由 - 因此,应该在路由配置中排在最后,因为任何后续路由将永远不会匹配。为了确保它也匹配“/”,包含了 url 参数的默认值。

default_route:
    pattern: /{url}
    defaults: { _controller: AcmeBundle:Default:index, url: "index" }
    requirements:
        url: ".+"

回答by dxb

I don't think it's possible with the standard routing component. Take a look to this bundle, it might help : https://github.com/hidenorigoto/DefaultRouteBundle

我认为标准路由组件是不可能的。看看这个包,它可能会有所帮助:https: //github.com/hiddenorigoto/DefaultRouteBundle

回答by Denis Gorbachev

// Symfony2 PR10

// Symfony2 PR10

in routing.yml:

在routing.yml:

default:
    pattern:  /{_controller}

It enables you to use this kind of urls: http://localhost/MySuperBundle:MyController:myview

它使您能够使用这种网址:http://localhost/MySuperBundle:MyController:myview

回答by mevdschee

Symfony2 standard routing component does not support it, but this bundle fills the gap Symfony1 left:

Symfony2 标准路由组件不支持它,但是这个包填补了 Symfony1 留下的空白:

https://github.com/LeaseWeb/LswDefaultRoutingBundle

https://github.com/LeaseWeb/LswDefaultRoutingBundle

It does what you expect. You can default route a bundle using this syntax:

它可以满足您的期望。您可以使用以下语法默认路由包:

FosUserBundle:
  resource: "@FosUserBundle"
  prefix:   /
  type:     default

It scans your bundle and automatically adds routes to your router table that you can debug by executing:

它会扫描您的包并自动将路由添加到您的路由器表中,您可以通过执行以下命令进行调试:

app/console router:debug

Example of automatically added default routes:

自动添加的默认路由示例:

[router] Current routes
Name                          Method Pattern
fos_user.user.login_check     ANY    /user/login_check.{_format}
fos_user.user.logout          ANY    /user/logout.{_format}
fos_user.user.login           ANY    /user/login.{_format}
...

You see that it also supports the automatic "format" selection by using a file extension (html, json or xml).

您会看到它还支持使用文件扩展名(html、json 或 xml)自动选择“格式”。

回答by Crozin

Here is an example: http://docs.symfony-reloaded.org/master/quick_tour/the_big_picture.html#routing

这是一个例子:http: //docs.symfony-reloaded.org/master/quick_tour/the_big_picture.html#routing

A route definition has only one mandatory parameter patternand three optionals parameters defaults, requirementsand options.

一个路由定义只有一个强制参数pattern和三个可选参数defaultsrequirements以及options

Here's a route from my own project:

这是我自己项目中的一条路线:

video:
    pattern:  /watch/{id}/{slug}
    defaults: { _controller: SiteBundle:Video:watch }
    requirements: { id: "\d+", slug: "[\w-]+" 

回答by Marc Morera Merino

Create a default route is not a good way of programming. Why? Because for this reason was implemented Exception. Symfony2 is built just to do right things in the right way.

创建默认路由并不是一种好的编程方式。为什么?因为这个原因才实施了Exception。Symfony2 的构建只是为了以正确的方式做正确的事情。

If you want to redirect all "not found" routes you should use exception, like NotFound404 or something similar. You can even customise this page at your own.

如果你想重定向所有“未找到”的路由,你应该使用异常,比如 NotFound404 或类似的东西。您甚至可以自己自定义此页面。

One route is for one purpose. Always. Other think is bad.

一条路线是为了一个目的。总是。其他认为不好。

回答by ken

Alternatively, you can use @Route annotation directly in a controller file. see https://github.com/sensio/SensioFrameworkExtraBundle/blob/master/Resources/doc/annotations/routing.rst

或者,您可以直接在控制器文件中使用 @Route 注释。见https://github.com/sensio/SensioFrameworkExtraBundle/blob/master/Resources/doc/annotations/routing.rst

As for the default routes, I think Symfony2 encourages explicit route mapping.

至于默认路由,我认为 Symfony2 鼓励显式路由映射。

回答by MFoster

You could create your own bundle that handled all requests and used URL parameters to construct a string to pass to the controller's forward method. But that's pretty crappy, I'd go with well defined routes, it keeps your URLs cleaner, and decouples the URL and controller names. If you rename a bundle or something, do you then have to refactor your URLs?

您可以创建自己的包来处理所有请求并使用 URL 参数来构造要传递给控制器​​的 forward 方法的字符串。但这很糟糕,我会使用定义明确的路由,它使您的 URL 更清晰,并将 URL 和控制器名称解耦。如果您重命名捆绑包或其他名称,那么您是否必须重构您的 URL?

回答by D H

If you want to create a "catch all", your best bet would be to hook on the KernelEvents::EXCEPTIONevent. This event gets triggered whenever an Exception falls through to the HttpKernel, this includes the NotFoundHttpExceptionthrown when the router cannot resolve a route to a Controller.

如果你想创建一个“包罗万象”,你最好的办法就是抓住这个KernelEvents::EXCEPTION事件。每当异常落入 时就会触发此事件HttpKernel,这包括NotFoundHttpException当路由器无法解析到控制器的路由时抛出的事件。

The effect would be similar to Symfony's stylized 404 page that gets rendered when you send the request through app_dev.php. Instead of returning a 404, you perform whatever logic you're looking to.

当您通过 app_dev.php 发送请求时,效果将类似于 Symfony 的风格化 404 页面。您无需返回 404,而是执行您想要的任何逻辑。

回答by luminol

It depends... Some of mine look like this:

这取决于......我的一些看起来像这样:

api_email:
resource: "@MApiBundle/Resources/config/routing_email.yml"
prefix: /

and some look like

有些看起来像

api_images:
path:     /images/{listingId}/{width}/{fileName}
defaults: { _controller: ApiBundle:Image:view, listingId: null, width: null, fileName: null }
methods:  [GET]
requirements:
    fileName: .+