symfony2 FOSRestBundle注释

时间:2011-10-24 07:38:11

标签: symfony fosrestbundle

是否有人在控制器中使用put,get,post,delete注释(https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Controller/Annotations/)。

我试图像这样使用它,但它仍然需要获取方法。 FOSRestBundle中那些注释的目的是什么

/**
 * @Route("/get/{id}", defaults={"_format" = "json"})
 * @Post
 */
public function getObject($id) {    
    $object = $this->getService()->findById($id);
     return $object;
}

2 个答案:

答案 0 :(得分:14)

我想分享有关所有注释的信息。

@ Get,@ Post,@ Put,@ Delete,@ Head,@ Pick 是@Route + @Method的快捷方式,而不是同时使用它们,您只需指定一个,例如:

    /**
     * @Get("/hello/{id}")
     * 
     */
    public function helloAction($id)
    {
        return array();
    }

@View 的信息位于doc:https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/3-listener-support.md

@View //Guess template name
@View("AcmeHelloBundle::layout.html.twig") //Load Resources/views/layout.html.twig
@View("AcmeHelloBundle::layout.html.twig", templateVar="test") // if returned data doesn't 
    // have a key (e.g. return array("string", 5) instead of default variable 'data', 
    // it's placed inside 'test' variable inside template.
@View(statusCode=204) // set HTTP header's status code

名称前缀可以添加到routing.yml文件中或作为注释添加。它还记录在案 - https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/6-automatic-route-generation_multiple-restful-controllers.md

  

有时,路由自动命名会导致路由名称冲突,所以   RestBundle路由集合提供了name_prefix(name的前缀)   xml / yml和@NamePrefix for annotation)参数:

  #src/Acme/HelloBundle/Resources/config/users_routes.yml comments:
     type:         rest
     resource:     "@AcmeHelloBundle\Controller\CommentsController"
     name_prefix:  api_
  

使用此配置,路由名称将变为:   api_vote_user_comment

@Prefix 在您拥有父资源并且需要在子级1之前添加前缀时特别有用。 例如:

父:

class UsersController extends Controller
{
    public function getUserAction($slug)
    {} // "get_user"   [GET] /users/{slug}
}

子:

class CommentsController extends Controller
{
    public function getCommentAction($slug, $id)
    {} // "get_user_comment"    [GET] 
}

现在,行为getCommentAction与 / users / {slug} / comments / {id} 路径对应。

使用@Prefix(“some_prefix”)生成的路径将是/ users / {slug} / some_prefix / comments / {id}

通过使用 @NoRoute 方法级注释,将不会生成路由。

答案 1 :(得分:2)

你不应该把id放在路由中(因为那相当于一个get)。相反,你应该这样做以强制通过$ _POST

发送id参数
/**
* @Route("/get", defaults={"_format" = "json"})
 * @Post
 */
public function getObject() {  
    $id = $this->Request::createFromGlobals()->request->get('id');
    $object = $this->getService()->findById($id);
    return $object;
}