Search code examples
phpslimslim-3

Slim 3 - how to use or-operator in the route?


How can I do 'or' in the route?

for instance, /about and /fr/about are pointing to the same objects/classes/methods. So instead of:

$app->get('/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

$app->get('/{language:[fr|en]+}/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

I tried with this:

$app->get('/{url:[a-zA-Z0-9\-]+}|/{language:[fr|en]+}/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

I get this error:

Type: FastRoute\BadRouteException
Message: Cannot use the same placeholder "url" twice
File: /var/www/mysite/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php

Any ideas what how to resolve this issue?

Or any solutions to avoid repeating the code?


Solution

  • If changing the order of the placeholders is possible for you, you could implement it in this manner:

    $app->get('/{url:[a-zA-Z0-9\-]+}[/{language:[en|fr]+}]', function($request, $response, $args) {
        // code here...
    });
    

    By "changing the order of the placeholders" I mean the url comes first, then the language, so instead of fr/about you use about/fr.

    The solution utilizes Slim's built-in optional segments: note the square brackets that wrap "language" placeholder.

    It, however, requires that the optional segments are placed at the end of the route, otherwise you get FastRoute\BadRouteException.