在symfony的控制器中设置获取请求参数的要求

问题描述 投票:0回答:3

我有一个处理 GET 请求的控制器。我需要为 GET 请求设置要求参数,例如: 'http://localhost/site/main?id=10&sort=asc

我的控制器类

class IndexController extends Controller {
`   /**
     * @Route
     * (
     *     "/site/main", 
     *     name="main"
     * )
     *
     * @Method("GET")
     */
    public function mainAction(Request $request) 
    {
        return new Response('', 200);
    }
}

我怎么能这么做?

UPD:我需要设置 URL 参数的要求,例如 id: "\d+", 排序:“\w+” ETC。 与 symfony 允许处理 POST 请求相同。

php symfony
3个回答
3
投票

您可以在“@Route”注释中指定要求,如下所示:

class IndexController extends Controller {

`   /**
     * @Route
     * (
     *     "/site/main", 
     *     name="main",
     *     requirements={
     *     "id": "\d+",
     *     "sort": "\w+"
     * })
     * )
     *
     * @Method("GET")
     */
    public function mainAction(Request $request) 
    {
        return new Response('', 200);
    }
}

0
投票

@Method 就是您所需要的http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html#route-method

如果您尝试通过 POST 使用此路由,您将遇到 404


0
投票

我不太明白你的问题。 但是,如果您需要的是为 GET 方法参数设置一个过滤机制,因为它已经可用于使用路由要求的 URL,我认为 Route 组件中没有现成的可用工具,如评论所述 @耀西

我必须自己做这种工作并使用这个。希望对你也有帮助

public function indexAction(Request $request)
{
    // Parameter names used in the current request
    $current_request_params=array_keys($request->query->all());

     // $ALLOWED_INDEX_PARAMS should be declared as Class static property array and hold names of the query parameters you want to allow for this method/action
    $unallowed_request_params=array_diff($current_request_params,PersonController::$ALLOWED_INDEX_PARAMS);

    if (!empty($unallowed_request_params))
    {
        $result=array("error"=>sprintf("Unknown parameters: %s. PLease check the API documentation for more details.",implode($unallowed_request_params,", ")));

        $jsonRsp=$this->get("serializer")->serialize($result,"json");

        return new Response($jsonRsp,Response::HTTP_BAD_REQUEST,array("Content-Type"=>"application/json"));
    }
    // We are sure all parameters are correct, process the query job ..
}
© www.soinside.com 2019 - 2024. All rights reserved.