fos rest custom get url in symfony2

fos rest custom get url in symfony2

我需要在休息时创建自定义 url api。我正在使用 fos 休息包。

自定义 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)

谁能帮我解决这个问题。如何形成这样的URLs.

我的控制器操作代码:

/*
 * @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__);
}

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

他们也会在完整的 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;

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

我想基本上您是希望 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;
    }

}