Search code examples
phpframeworksslim

Slim Framework: Route only accepted parameters


I want to define two routes based on route parameters, for example:

$app->get('/{param}', function (Request $request, Response $response) {
  // This route can only accept params like: colors, finish, material
}

// And to have another similar but to accept different params

$app->get('/{param2}', function (Request $request, Response $response) {
  // This route can only accept params like: jobs, customers
}

I can check which param it is in route callbacks, but I don't think in this situation both route callbacks are being invoked, right? i.e I can check that in the first route, but the callback for the second route will not be invoked.

Is there something I can add to the get object to fulfill what I want?


Solution

  • You can define route params in a way to match certain patterns. In your case, this patterns are predefined set of words:

    $app->get('/{param:colors|finish|materials}', function ( $request, $response, $args) {
      // This route can only accept params like: colors, finish, material
        return "First route with param: " . $args['param'];
    });
    
    // And having another route similar but to another params
    
    $app->get('/{param:jobs|customers}', function ($request, $response, $args) {
      // This route can only accept params like: jobs, customers
        return "Second route with param: " . $args['param'];
    });
    

    You can read more about route patterns in FastRoute documentation.