简体   繁体   中英

How to get a parameter from a url in Silex

I'm trying to get a parameter from an url in a Silex app.

Here's my connect method of my controller :

public function connect(Application $app)
{
    $controllers = $app['controllers_factory'];

    $controllers->get('/list/pois/{id}', array($this, 'actionPoisList'))
        ->before(array($this, 'controlerAuthentification'));

    return $controllers;
}

Here I'm trying to catch this parameter by doing this:

/**
 * @param Application $app
 * @return \Symfony\Component\HttpFoundation\JsonResponse
 */
public function actionPoisList(Application $app){

    return $app->json($app->escape($app['id']));
}

Obviously, its not working so any alternative please. Thanks

The parameters in URLs are automagically passed into your controller routes if you specify them in the parameter's list:

/**
 * @param Application $app
 * @return \Symfony\Component\HttpFoundation\JsonResponse
 */
public function actionPoisList(Application $app, $id){

    return $app->json($app->escape($id));
}

Take into account that the route parameter and the function parameter should be named exactly the same.

This is most commonly referred as an url slug, and silex documentation is taking that into account here

basically you just pass the variable in the function your route resolves to

$app->get('/blog/{id}', function (Silex\Application $app, $id) {
  // access $id here
})

For people not familiar enough with the Silex framework, I thought that having the parameter in the signature of the controller's action was blurring its origin.

I personally prefer to not include it in the method's signature and instead retrieving it via the request object, which highlights the fact that the parameter is included in the route. This can be done with the attribute property:

public function actionPoisList(Request $request) {
    $id = $request->attributes->get('id');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM