4

如果我想让每个 url 调用除了我在对/ExplicitControllerName/ExplicitActionToRun采取行动之后定义的调用之外......路由看起来会是什么样子。

例如一些伪代码:

default_pathing:
    pattern:  /{controller}/{action}
    defaults: { _controller: Bundle:Default:index }

所以如果我去 www.example.com/Page/About

它会调用我的控制器

class Page extends Controller
{
    public AboutAction()
    {
        // Called by above URL
    }
}

这个问题不回答:Symfony2/routing/use parameters as Controller or Action name

想象一下,我有 100 个页面,其中有很多子路由页面每次都在做几乎相同的路由。我想为所有这 100 个控制器做 1 个路由。我们将如何做到这一点?

PS 我真的很喜欢 C#.NET MVC 4.0 路由之类的东西,它允许您为您可能拥有的典型设置设置路由,即使至少它用于开发

4

2 回答 2

2

您的问题并不完全清楚,但这里有一些提示。

我可以想象您要解决的两个用例:

1)您有很多某种 CMS 页面,例如您的 about 示例,这些页面没有太多逻辑,只是呈现一些视图,在这种情况下,您会像:

class CMSPageController
{
    public function renderPage($pageSlug)
    {
        $page = $this->cmsPageRepository->findBySlug($pageSlug);

        // your logic to render the view
    }
}

以及相应的路由配置:

<route id="cms_page_view" pattern="/cms/{pageSlug}">
  <default key="_controller">cms_page.controller.page:renderPage</default>
  <requirement key="_method">GET</requirement>
  <requirement key="slug">[0-9a-zA-Z\-\.\/]+</requirement>
</route>

2)您有更复杂的要求,和/或遵循特定模式来命名您的控制器/动作,因此您需要编写自定义UrlMatcherInterface实现。查看本机实现以了解从哪里开始。它可以让你定义一个后备。

于 2013-10-08T13:58:56.360 回答
0

This can be achieved using either SensioFrameworkExtraBundle's @Route annotation on class- and method-level excessively...

... or more elegant with less annotations using FOSRestBundle's automatic route generation with implicit resource names. Maybe you'll need to correct some of the generated routes using some of FOSRestBundle's manual route definition annotations.

Both methods originally still leave the need to explicitly add the route resources to your app/config/routing.yml.

Example import for @Route

# import routes from a controller directory
blog:
    resource: "@SensioBlogBundle/Controller"
    type:     annotation

Example import for FOSRestBundle

users:
    type:     rest
    resource: Acme\HelloBundle\Controller\UsersController

You could work around having to import all the resources by:

  • introducing a custom annotation (class-level)
  • creating a compiler pass or a custom route loader in which you ...
  • use the Finder to find all controller classes in all bundles with that annotation
  • finally add all those as resources with type annotation/rest to the route collection in there

If you don't plan to use hundreds of controllers and don't have too much experience with compiler-passes, custom annotations, ... etc. you'll definitely be faster just registering the resources in the routing config.

于 2013-10-08T20:18:35.940 回答