fos-rest自定义获取symfony2中的url


fos rest custom get url in symfony2

我需要在我的rest api中创建一个自定义url。我正在使用fos rest捆绑包。

自定义URL类似于:

http://myapi.com/api/v1/public/users/confirm?cd=<some_code>.json

我试过:

@GET("/users/confirm?cd={cd}")

当我运行时:

php /app/console route:debug

我得到了这个:

...
....
get_confirm GET ANY ANY  /api/v1/public/users/confirm?cd={cd}.{_format}
...
...

但在我的测试中,当我尝试点击这个URL时,我得到了:

No route found for &quot;GET /api/v1/public/users/confirm&quot; (404 Not Found)

有人能帮我吗。如何形成这样的URL。

我的控制器操作代码:

/*
 * @GET("/users/confirm?cd={cd}")
 */
public function getConfirmAction($cd) {
    //Some code for user confirmation
    return return View::create(array('successmessage'=>'Your account has been verified successfully. Please login.', Codes::HTTP_OK);
}

PHPUnit测试代码:

public function testGetConfirmThrowsInvalidArgumentException() {
    $this->client->request(
                'GET', '/api/v1/public/users/confirm?cd=abcd123.json'
        );
        $response = $this->client->getResponse();
        print_r($response->getContent());
        exit(__METHOD__);
}

同意@john评论:您不需要将查询参数添加到路由定义

我想基本上你是希望有一个参数总是提供的网址。如果这是您的需求,那么FOSRestBundle有一个很酷的功能,称为param fetcher。有了它,您可以用注释定义查询字符串参数,允许它们为null或不为null,设置默认值,定义需求。

对于您的案例,如果您希望cd是一个数字,那么您可以将注释作为

@QueryParam(name="cd", nullable=true, requirements="'d+")

示例代码见下例

/*
* function desc
* @QueryParam(name="cd", nullable=true, requirements="'d+")
* @param ParamFetcher $paramFetcher
*/
public function getConfirmActionAction(ParamFetcher $paramFetcher)
{
   //access the parameter here
    foreach ($paramFetcher->all() as $name => $value) {
        echo $name."==>". $value;
    }
}

您不需要将查询参数添加到路由定义中

它们也会出现在完整的url之后,例如".json"之后

即:

/api/v1/public/users/confirm.json?cd=ejwffw

所以我没有注释路由定义的经验,但它应该是这样的:

@GET("/users/confirm.{_format}")

在您的操作中,您可以通过请求访问您的参数

类似

$request=$this->getRequest();
$code = $request->get('cd') ? $request->get('cd') : false;