Search code examples
silex

Silex route interchangeable parameters


Given that I had a route that must accept either the code or the id of the object, is there any way in silex that I can detect which was passed to the route (numeric or not numeric) and then send either one variable or the other?

Eg. /route/1 -> id for USA on the database

I send $id = 1 and $code = null to the controller

/route/US -> code for USA on the database

I send $id = null and $code = 'US' to the controller

I tried something like this, but it won't work

$apiRoutesV2
    ->get('/route/{code}{id}', 'controllers.myController:getIndex')
    ->value('id', null)
    ->assert('id', '[0-9]+')
    ->value('code', null)
    ->assert('code', '[a-zA-Z]+');

Solution

  • If both id and code can be empty, you can make one route with default values:

    $app
        ->get('/route/{code}{id}', 'controllers.myController:getIndex')
        ->value('id', '')
        ->assert('id', '[0-9]*')
        ->value('code', '')
        ->assert('code', '[a-zA-Z]*');
    

    If one of parameters should be filled add 2 routes:

    $app
        ->get('/route/{id}', 'controllers.myController:getIndex')
        ->assert('id', '[0-9]+');
    
    $app
        ->get('/route/{code}', 'controllers.myController:getIndex')
        ->assert('code', '[a-zA-Z]+');