使用默认占位符的symfony2路由

时间:2013-03-05 10:03:05

标签: php symfony routing placeholder

应用程序/配置/ routing_dev.yml:

people:
    resource: "@myPeopleBundle/Resources/config/routing.yml"
    prefix:   /people

myPeopleBundle /资源/配置/ routing.yml中:

people_homepage:
    pattern:  /{name}
    defaults: { _controller: myPeopleBundle:Default:index, name: Foo }

people_homepage2:
    pattern:  /
    defaults: { _controller: myPeopleBundle:Default:index, name: Bar }

myPeopleBundle:控制器:DefaultController.php:

...
public function indexAction($name) {
    return $this->render('myPeopleBundle:Default:index.html.twig', array('name' => $name));
}
...

myPeopleBundle:默认:index.html.twig:

Hello {{ name }}!

web/app_dev.php/people ->你好Foo!
web/app_dev.php/people/ -> Hello Bar!

为什么会有所不同? people_homepage路由为何与第二个(web/app_dev.php/people/)网址不匹配?

但如果我将prefix设置为/,我会得到相同的输出:
web/app_dev.php ->你好Foo!
web/app_dev.php/ ->你好Foo!

1 个答案:

答案 0 :(得分:3)

如果你看appdevUrlMatcher.php,你会看到类似的东西:

    // people_homepage
    if (preg_match('#^/people(?:/(?P<name>[^/]++))?$#s', $pathinfo, $matches)) {
        return $this->mergeDefaults(array_replace($matches, array('_route' => 'people_homepage')), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DefaultController::indexAction',  'name' => 'Foo',));
    }

    // people_homepage2
    if (rtrim($pathinfo, '/') === '/people') {
        if (substr($pathinfo, -1) !== '/') {
            return $this->redirect($pathinfo.'/', 'people_homepage2');
        }

        return array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DefaultController::indexAction',  'name' => 'Bar',  '_route' => 'people_homepage2',);
    }

您可以看到路线/people/people_homepage不匹配,但会与/people/people/test

匹配

如果您改变路线的顺序

,那么您正在做的事情会更有意义
people_homepage2:
    pattern:  /
    defaults: { _controller: myPeopleBundle:Default:index, name: Bar }

people_homepage:
    pattern:  /{name}
    defaults: { _controller: myPeopleBundle:Default:index, name: Foo }

使用此配置,您将拥有:

/people == /people/ ---&gt; people_homepage2

/people/test ---&gt; people_homepage