Symfony-使用FOSRestBundle和body_listener的过滤器请求没有注释?

卡特里娜飓风

我在FOSRestBundle中使用Symfony2。是否可以不使用批注而具有@QueryParam和@RequestParam批注的功能?

我正在尝试构建一个json api(format),所以我想允许查询参数,包括include,page,filter,fields和sort。我理想的处理方式是:

  1. 使用format_listener来检测它是json。
  2. 使用自定义body_listener json处理程序来处理请求,使其类似于this
  3. 让控制器验证动作函数中的查询/请求参数,并抛出一个异常,如果无效,则由异常控制器处理。(body_listener将充当帮助者,使控制器中的请求中的数据提取更加容易,但是控制器将决定如何处理该数据。)

我主要停留在如何制作自定义body_listener上。我不确定是否需要创建自定义的解码器或规范化器,以及该类的外观,因为它们没有提供任何示例。

控制器外观的大致代码:

<?php
namespace CoreBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use FOS\RestBundle\Context\Context;
use Psr\Http\Message\ServerRequestInterface;

class SiteController extends FOSRestController
{   
    public function getAction($id, ServerRequestInterface $request)
    {
        try {
            // Validate $request. This is where the query/request
            // param annotation functionality would be replaced.
        } catch (Exception $e) {
            throw new InvalidRequestException($e);
        }

        $siteService = $this->get('app.site_service');
        $site = $siteService->getSite($id);

        $context = new Context();

        $context->setVersion($request->getVersion());
        // Ex: /sites/63?fields[sites]=name,address&fields[company]=foo,bar
        if ($request->hasIncludeFields()) {
            $context->addAttribute('include_fields', $request->getIncludeFields()); // Or however to do this
        }

        $view = new View($site, 200);

        $view->setContext($context);

        return $view;
    }
}
阿尔特姆·茹拉夫列夫(Artem Zhuravlev)

您可以在参数获取程序中动态定义参数。文档中对其进行了描述

例如:

带有注释:

<?php

namespace ContentBundle\Controller\API;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Request\ParamFetcher;

class PostController extends FOSRestController
{
    /**
     * @QueryParam(name="sort", requirements="(asc|desc)", allowBlank=false, default="asc", description="Sort direction")
     */
    public function getPostsAction(ParamFetcher $paramFetcher)
    {
        $sort = $paramFetcher->get('sort');
    }
}

没有注释:

<?php

namespace ContentBundle\Controller\API;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Request\ParamFetcher;

class PostController extends FOSRestController
{
   public function getPostsAction(ParamFetcher $paramFetcher)
    {
        $sort = new QueryParam();
        $sort->name = 'sort';
        $sort->requirements = '(asc|desc)';
        $sort->allowBlank = false;
        $sort->default = 'asc';
        $sort->description = 'Sort direction';

        $paramFetcher->addParam($sort);

        $param = $paramFetcher->get('sort');
        //
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章