Search code examples
phpregexroutessilex

Silex 2: RegEx in routing


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');

Solution

  • 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');