Search code examples
phpslim-3

PHP : Slim Combination of Optional and Required Param


I want follwing type of route.

$app->get('/FetchImages/{catid}[/{subcatid}]/{page}', function ($request, $response, $args) {
    //Code
});

In Route I want following:

  • Category - Mandatory
  • SubCategory - Optional
  • Page - Mandatory

Can I do it in one route? If so, how can it be achieved? I want to have one function for these paths:

{catid}/{page}
{catid}/{subcatid}/{page}

Solution

  • You can't have mandatory placeholders after optional. If you try, fastRoute (router, utilized by Slim) will give you an error.

    And even if we abstract from Slim and fastRoute, I suggest you reconsider the URL structure of your API. It is natural that mandatory comes first, optional comes later.

    To be able to use same callback for the routes, I suggest you pass page as query parameter:

    $this->get('/FetchImages/{categoryId}[/{subcategoryId}]', function($request, $response, $args) {
    
        $categoryId = $args['categoryId'];
        $subcategoryId = $args['subcategoryId'];
    
        //  Get requested page value.
        //  It defaults to null if no page specified
        $page = $request->getQueryParam('page', null);
    
    });
    

    And send request like this:

    GET http://myapp.com/FetchImages/kittens/dangerous?page=2

    In this case you're free to pass or skip page, and URL structure is still quite clean.