2012-12-08 36 views
8

使用Symfony2和FOSRestBundle我試圖實現API方法,這些API方法在路由中定義了一些固定參數以及查詢字符串中可能存在的一些可選參數。使用Symfony中的FOSRestBundle混合路由和查詢參數

例如:

http://somesite.com/api/method/a/b 
http://somesite.com/api/method/c/d?x=1&y=2 

the documentation for FOSRestBundle,ParamFetcher是要做到這一點,利用@QueryParam標註的正確方法。不過,我已經有一個控制器,定義如下:

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use FOS\RestBundle\Controller\Annotations\Get; 
use FOS\RestBundle\Controller\Annotations\View; 

class MyController extends Controller 
{ 

    /** 
    * @Get("/method/{a}/{b}") 
    * @View() 
    */ 
    public function getMethodAction($a, $b) 
    { 
    // do stuff 

    return array('foo' => 'bar'); 
    } 

} 

現在看來,我需要能夠獲得訪問ParamFetcher的實例,但我不知道如何(以及谷歌搜索並沒有幫助太多) 。我從文檔中知道,我可以簡單地改變方法簽名來併入ParamFetcher,但是,當我這樣做時,它將參數移動到查詢字符串中,這是我不能擁有的。

是否有混合兩者的方法,還是應該放棄ParamFetcher並直接使用Symfomy的內置Request對象直接檢查請求?

回答

12

這個問題是相當古老的,你可能已經找到了解決方案,但自從我通過谷歌搜索來到這裏,並知道我會貢獻的答案。

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use FOS\RestBundle\Request\ParamFetcher; 
use FOS\RestBundle\Controller\Annotations\QueryParam; 
use Nelmio\ApiDocBundle\Annotation\ApiDoc; 

class DefaultController extends Controller 
{ 
    /** 
    * Returns a collection of Task 
    * 
    * @QueryParam(name="projectId", nullable=true, requirements="\d+") 
    * @QueryParam(name="name", nullable=true, description="Project Name") 
    * @QueryParam(name="assignee", nullable=true) 
    * @QueryParam(name="depth", nullable=true) 
    *   * 
    * @param ParamFetcher $paramFetcher 
    * @ApiDoc() 
    * 
    * @return JsonResponse 
    */ 
    public function cgetTaskAction(ParamFetcher $paramFetcher) 
    { 
     foreach ($paramFetcher->all() as $criterionName => $criterionValue) { 
      // some logic here, eg building query 
     } 

     $results = // query database using criteria from above 

     // this is just a simple example how to return data 
     return new JsonResponse($results); 
    } 
} 
+1

感謝您的跟進 - 我終於弄清楚了這一點,並忽略了回來。 – futureal

5

只是想發佈一個答案,因爲原來的答案只使用QueryParams,並使用QueryParams問題連同RouteParams。

如果您想要使用路徑參數和查詢參數,可以使用ParamFetcher作爲動作的第一個參數,並稍後添加路由參數。

我還沒有找到一種方法將路徑參數添加到paramFetcher。

/* 
* @Route("/term/{termId}", requirements={"termId" = "[a-z0-9]+"}) 
* 
* @QueryParam(name="limit", requirements="\d+", default="30", description="How many documents to return.") 
* 
* @Method("GET") 
* 
* @param ParamFetcherInterface $paramFetcher 
* @param $termId 
* @return array() 
*/ 
public function getTermFeedAction(ParamFetcherInterface $paramFetcher, $termId) { 
    // access $termId over the method parameter 
    // access the @queryparams via the $paramFetcher 

} 
+0

更好的答案,因爲它不會中斷路由參數注入。 – Ryall