30

I've been using Silex for a day, and I have the first "stupid" question. If I have:

$app->get('/cities/{city_id}.json', function(Request $request, $city_id) use($app) {
    ....
})
->bind('city')
->middleware($checkHash);

I want to get all the parameters (city_id) included in the middleware:

$checkHash = function (Request $request) use ($app) {

    // not loading city_id, just the parameter after the ?
    $params = $request->query->all();

    ....
}

So, how do I get city_id (both the parameter name and its value) inside the middleware. I'm going to have like 30 actions, so I need something usable and maintainable.

What am I missing?

thanks a lot!

Solution

We need to get those extra parameters of $request->attributes

$checkHash = function (Request $request) use ($app) {

    // GET params
    $params = $request->query->all();

    // Params which are on the PATH_INFO
    foreach ( $request->attributes as $key => $val )
    {
        // on the attributes ParamaterBag there are other parameters
        // which start with a _parametername. We don't want them.
        if ( strpos($key, '_') != 0 )
        {
            $params[ $key ] = $val;
        }
    }

    // now we have all the parameters of the url on $params

    ...

});
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
fesja
  • 3,313
  • 6
  • 30
  • 42

1 Answers1

64

In Request object you have access to multiple parameter bags, in particular:

  • $request->query - the GET parameters
  • $request->request - the POST parameters
  • $request->attributes - the request attributes (includes parameters parsed from the PATH_INFO)

$request->query contains GET parameters only. city_id is not a GET parameter. It's an attribute parsed from the PATH_INFO.

Silex uses several Symfony Components. Request and Response classes are part of the HttpFoundation. Learn more about it from Symfony docs:

Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • thanks kuba, you pointed me to the solution. I've added it to the question. – fesja May 05 '12 at 16:28
  • 3
    One remark. Always use strict comparators with strpos ("!==" and not "!="). Remember than null and 0 are "equal" when compared with == (but are not equal compared with ===). – Jakub Zalas May 05 '12 at 17:20