Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I obtain all the GET parameters on Silex?

Tags:

php

symfony

silex

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      ...  }); 
like image 217
fesja Avatar asked May 04 '12 19:05

fesja


1 Answers

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:

  • The HttpFoundation Component
  • HttpFoundation API
  • Request API
like image 130
Jakub Zalas Avatar answered Sep 18 '22 15:09

Jakub Zalas