Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - nested resources best practice

Using Yii2 framework I cannot find any built-in functionality to implement something called nested resources in Ruby on Rails (http://guides.rubyonrails.org/routing.html#nested-resources)

For example, an Article has many Comments. So I want that comments related to an article will be accessed via /articles/1/comments URL when index action is used; via /articles/1/comments/create when create action is used and so on...

Do I have to add multiple action-methods to ArticlesController called actionIndexComments(), actionCreateComment()... ?

Or should I pass an ?article_id=1 parameter via GET and use it for filtering in CommentsController ?

Or should I maybe implement custom UrlManager class that can deal with nested routes? (maybe someone has already implemented it?)

What is the best practice for now?

like image 747
Andrey Pesoshin Avatar asked Jan 06 '15 11:01

Andrey Pesoshin


2 Answers

You should be able to do this easily with the UrlManager. It also depends on where you want to put the actual actions. You can put them either in a article controller or comment controller

For example for the comments controller you can define rules like this:

'article/<article_id:\d+>/comments/create/' => 'comment/create',
'article/<article_id:\d+>/comments/' => 'comment/index',

In both cases you can access the article_id (in GET) in the create or index actions. You can do exactly the same thing if you want to put the actions in the article.

like image 200
Mihai P. Avatar answered Sep 28 '22 06:09

Mihai P.


For more universe:

'GET,HEAD v1/articles/<id:\d+>/comments' =>
    'v1/articles/comment/index',
'GET,HEAD v1/<article/<id:\d+>/comments/<id:\d+>' =>
    'v1/articles/comment/view',
'POST v1/articles/<id:\d+>/comments' =>
    'v1/articles/comment/create',
'PUT,PATCH v1/article/<id:\d+>/comments' =>
    'v1/articles/comment/update',
'DELETE v1/article/<id:\d+>/comments' =>
    'v1/articles/comment/delete',
like image 42
jamlee Avatar answered Sep 28 '22 08:09

jamlee