Reputation: 157
Is it possible to use RegEx in Silex 2 routings?
I need to do something like this:
$this->get('/(adios|goodbay)', function (Request $request) use ($app) {
return $app['twig']->render('bye.html.twig', []);
})->bind('bye');
Upvotes: 2
Views: 1800
Reputation: 29431
Given the 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.
So I would say that it's possible to use regex as you did in the question.
Upvotes: 0
Reputation: 3590
As stated by Thomas, yes you can. The important part of the documentation are 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.
For example:
$app->get('/blog/{postId}/{commentId}', function ($postId, $commentId) {
// ...
})
->assert('postId', '\d+')
->assert('commentId', '\d+');
So, in your case the definition of the route would be something like:
$this->get('/{bye}', function (Request $request) use ($app) {
return $app['twig']->render('bye.html.twig', []);
})
->assert('bye', '^(adios|goodbye)$')
->bind('bye');
If you also want to know the value of the parameter, just pass it to the controller (the parameter name must match the name of the parameter in the route definition):
$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');
Upvotes: 5