本文介绍了Symfony2中基于约定的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习在Symfony2中路由如何工作,到目前为止,我所阅读的所有内容都具有这样的示例:

 博客:
路径:/ blog / {page}
默认值:{_controller:AcmeBlogBu​​ndle:Blog:index,page:1}

这会将请求发送到/ blog / 123到AcmeBlogBu​​ndle Blog控制器的 index动作,并将123参数作为 page参数传递给该控制器动作。如果未传递任何页面参数,则该页面默认为1。



这很好,但是如果您只想通过一个基于约定的路由系统该怎么办?这样的事情:

  / {bundle} / {controller} / {action} 

因此,对于这样的URL:

  / acme / blog / index 

然后它将调用AcmeBlogBu​​ndle Blog控制器的索引操作。 / p>

不需要特定的路由配置,它只是从URL推断出包,控制器和操作。因此,您可以继续添加捆绑,控制器和操作,而无需修改路由配置。



如果不可能,您至少可以从URL推断出控制器和动作吗?例如,也许您需要一条专门标识捆绑商品的路线,但是我们可以从URL获取控制器和动作吗?



我阅读了Symfony的 The Book 页面,但我想不出一种解决方法。 / p>

解决方案

没办法。



但是您应该看一下注释,因为它简化了配置路由的过程道路。直接附加到操作上,在配置和代码之间不乏不足。


I'm trying to learn learn how routing works in Symfony2, and so far everything I've read has examples like this:

blog:
    path:      /blog/{page}
    defaults:  { _controller: AcmeBlogBundle:Blog:index, page: 1 }

This routes requests to /blog/123 to the AcmeBlogBundle Blog controller's "index" action, and passes the 123 parameter as the "page" parameter to that controller action. If no page parameter is passed, then the page defaults to 1.

That's all well and good, but what if you want to simply have a convention based routing system that passes things through like this:

/{bundle}/{controller}/{action}

So, for a URL like this:

/acme/blog/index

It would then call AcmeBlogBundle Blog controller's "index" action.

No specific routing configuration is necessary, it simply infers the bundle, controller, and action from the URL. So you can continue adding bundles, controllers, and actions, and you don't need to modify the routing configuration. It just works.

If this isn't possible, can you at least infer the controller and action from the URL? E.g., perhaps you need a route that specifically identifies the bundle, but can we get the controller and action from the URL?

I read through the Symfony "The Book" page about routing, and I couldn't figure out a way to do this.

解决方案

No way. This was considered as bad practice and so it was removed from symfony.

But you should take a look at the @Route annotation, as it simplifies configuring routes in such a nice way. Directly attached to the action, there is no lack between config and code.

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

07-30 22:53