symfony2 FOSRestBundle annotations

user257980 picture user257980 · Oct 24, 2011 · Viewed 11.4k times · Source

Is anyone used put, get, post, delete annotations(https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Controller/Annotations/) in controller.

I'm trying to use it like this, but it still takes get methods. What is the purpose of those Annotations in FOSRestBundle

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

Answer

Dattaya picture Dattaya · Mar 29, 2012

I want to share info about all annotations.

@Get, @Post, @Put, @Delete, @Head, @Patch are shortcuts for @Route + @Method, instead of using them both, you can just specify one, e.g.:

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

Info about @View is in 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

Name prefix can be added either to routing.yml file or as a annotation. It is also documented - https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/6-automatic-route-generation_multiple-restful-controllers.md :

Sometimes, routes auto-naming will lead to route names collisions, so RestBundle route collections provides a name_prefix (name-prefix for xml/yml and @NamePrefix for annotations) parameter:

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

With this configuration, route name would become: api_vote_user_comment

@Prefix is especially useful when you have parent resource and need to add prefix before child one. Example:

parent:

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

child:

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

Now the action getCommentAction corresponds with /users/{slug}/comments/{id} path.

With @Prefix("some_prefix") generated path will be /users/{slug}/some_prefix/comments/{id}

And by using the @NoRoute method-level annotation, route won't be generated.