2012-05-04 58 views
26

我一直在使用Silex一天,我有第一個「愚蠢」的問題。如果我有:如何獲取Silex上的所有GET參數?

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

我想獲得的所有參數(city_id)包含在中間件:

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

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

    .... 
} 

所以,我怎麼city_id(參數名稱和值兩者)內中間件。我會有30個動作,所以我需要一些可用和可維護的東西。

我錯過了什麼?

非常感謝!

解決方案

我們需要得到$請求 - 這些額外的參數>屬性

$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 

    ... 

}); 
+0

它看起來像 - >中間件()不存在了? – Tobias

回答

60

Request對象,您可以訪問多個參數袋,特別是:

  • $request->query - GET參數
  • $request->request - 的POST參數
  • $request->attributes - 請求屬性(包括從所述解析的PATH_INFO參數)

$request->query僅包含GET參數。 city_id不是GET參數。它是從PATH_INFO解析的屬性。

Silex使用幾個Symfony Components。請求和響應類是HttpFoundation的一部分。瞭解更多關於它的Symfony文檔:

+0

感謝庫巴,你指出我的解決方案。我已將它添加到問題中。 – fesja

+3

一句話。始終使用strpos(「!==」而不是「!=」)的嚴格比較器。記住比null和0與==相比「相等」(但與===相比不相等)。 –