Silex 2:路由中的 RegEx

Silex 2: RegEx in routing

是否可以在 Silex 2 路由中使用 RegEx?

我需要做这样的事情:

$this->get('/(adios|goodbay)', function (Request $request) use ($app) {
    return $app['twig']->render('bye.html.twig', []);
})->bind('bye');

鉴于 docPage 8:

In Silex you define a route and the controller that is called when that route is matched. A route pattern consists of:

  • Pattern : The route pattern defines a path that points to a resource. The pattern can include variable parts and you are able to set RegExp requirements for them.

所以我想说可以像您在问题中那样使用正则表达式。

正如托马斯所说,是的,你可以。文档的重要部分是 route requirements:

In some cases you may want to only match certain expressions. You can define requirements using regular expressions by calling assert on the Controller object, which is returned by the routing methods.

例如:

$app->get('/blog/{postId}/{commentId}', function ($postId, $commentId) {
    // ...
})
->assert('postId', '\d+')
->assert('commentId', '\d+');

因此,在您的情况下,路线的定义类似于:

$this->get('/{bye}', function (Request $request) use ($app) {
    return $app['twig']->render('bye.html.twig', []);
})
->assert('bye', '^(adios|goodbye)$')
->bind('bye');

如果你也想知道参数的值,直接传给controller即可(参数名必须和路由定义中的参数名一致):

$this->get('/{bye}', function (Request $request, $bye) use ($app) {
    if ($bye === 'adios') {
      $sentence = "eso es todo amigos!";
    }
    else {
      $sentence = "that's all folks!";
    }

    return $app['twig']->render('bye.html.twig', ["sentence" => $sentence]);
})
->assert('bye', '^(adios|goodbye)$')
->bind('bye');