Search code examples
phpyii2nested-resources

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?


Solution

  • 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.