[英]fos rest custom get url in symfony2
我需要在我的rest api中创建一个自定义网址。 我正在使用fos rest bundle。
自定义网址如下:
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 "GET /api/v1/public/users/confirm" (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);
}
PHPUnitTest代码:
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注释: 您无需将queryparameters添加到您的路由定义中
我想基本上您正在寻找一个始终随URL提供的参数。 如果这是您的要求,则FOSRestBundle具有很酷的功能,称为param fetcher 。 使用它,您可以定义带有注释的查询字符串参数,允许它们为空或不可以,设置默认值,定义需求。
对于您的情况,如果您希望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;
}
}
您不需要将queryparameters添加到您的路由定义中
它们也会出现在完整网址之后,例如在“ .json”之后
即:
/api/v1/public/users/confirm.json?cd=ejwffw
所以我没有使用注释路由定义的经验,但是应该这样:
@GET("/users/confirm.{_format}")
在您的操作中,您可以通过请求访问参数
像:
$request=$this->getRequest();
$code = $request->get('cd') ? $request->get('cd') : false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.