Symfony2: the easiest way to get a RESTful URL

I currently have the usual Controller / Action structure:

BlogController:

/blog/list /blog/create /blog/detail/my-blog-hash 

And PostController

 /post/create /post/detail/my-post-hash 

I would like a URL to view the blog in detail:

 /blog/detail/my-blog-hash/post/my-post-hash 

I know there is a RESTBundle, but this is an overly complex phenomenon for IMO, and there are some real problems with routes and form validation that I could not solve (even with the help of the guys from IRC). I don't need access points for JSON, serializers, special views, etc. I just need to somehow drain the controllers.

Can someone help me?

+6
source share
4 answers

I installed RestBundle, after several hours of work, I uninstalled it again due to the inflexibility of the routes (at least I did not know how to configure the routes accordingly).

After that, I set up the routes in the same way as in regular controllers. Therefore, I added such routing annotations:

 // BlogController @ORM\Route("blogs/{blogHash}", name="blog_detail") public function detailAction(Blog $blog) 

and

 // PostController @ORM\Route("blogs/{blogHash}/post/{postHash}", name="blog_post_detail") public function detailAction($blogHash, $postHash) 

Important: you must include PostController before BlogController in your routing configuration.

0
source

This does not answer your specific question, but I would recommend a cleaner URL that is more RESTful.

For working with blogs, they generally interact with the base resource /blogs .

POST /blogs to create a blog.

GET /blogs to list all blogs.

To work with a specific blog, you indicate which blog.

GET /blogs/:id to get detailed information for a specific blog.

Now indicate which subresource of the blog you want to interact with.

POST /blogs/:id/posts to create a new post.

GET /blogs/:id/posts/:id to get detailed post information for a specific blog.

+8
source

I think you have two resources: blogs and posts.

In a RESTful route, action is implied by an http verb. I understand that you are not in Rails, but these simple tables illustrate the β€œRails way” for REST and RESTful nested resources:

http://edgeguides.rubyonrails.org/routing.html#crud-verbs-and-actions

http://edgeguides.rubyonrails.org/routing.html#nested-resources

Very clean.

+1
source

Can you not just map the route with two parameters for the action of the part?

We use annotations for our routes, so I know :) But I believe that the essence of this method is the same for all methods.

 /** * @Route("/blog/{blog_hash}/post/{post_hash}", name="post_detail") */ 

Then the problem is that you need to get a post blog to pass two arguments to the URL helper when showing links to it, and not just the post itself. But I do not think there is another way.

The detailed action is to verify that the given URL is valid. I doubt sf2 will do this for you.

0
source

Source: https://habr.com/ru/post/905870/


All Articles