-->

混合使用FOSRestBundle与Symfony的路线和查询参数(Mixing route and

2019-08-03 17:47发布

使用Symfony2中和FOSRestBundle我试图实现一个具有在路线与可能在查询字符串中存在着一些可选的参数一起定义的固定参数的一些的API方法。

例如:

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

根据对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对象?

Answer 1:

这个问题是很老,你可能会发现一个解决方案已经但是因为我来到这里通过谷歌搜索,知道答案,我会做出贡献。

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);
    }
}


Answer 2:

只是想发布一个答案,因为原来的答案只使用QueryParams,并使用QueryParams问题连同RouteParams。

如果您想使用的路由PARAMS和查询参数,你可以使用ParamFetcher作为第一个参数的动作,后来添加路由参数。

我还没有找到一种方法,路线PARAMS添加到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

}


文章来源: Mixing route and query parameters using FOSRestBundle with Symfony