Yii2 - Best Resource Practices

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

For example, Article has a lot of comments . Therefore, I want the comments associated with the article to be accessible through the /articles/1/commentsURL when the action is used index; through /articles/1/comments/createwhen action is used createetc ...

Do I need to add several action methods to the ArticlesController called actionIndexComments(), actionCreateComment()...?

Or do I need to pass a parameter ?article_id=1via GET and use it to filter in a CommentsController ?

Or should I implement my own class UrlManagerthat can work with nested routes? (maybe someone has already implemented it?)

What is the best practice right now?

+4
source share
3 answers

You can do this easily with UrlManager. It also depends on where you want to put the actual actions. You can put them in the product controller or comment controller

For example, for a comment controller, you can define the following rules:

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

article_id ( GET) create index. , .

+5

:

'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',
+4

REST Api, yii\rest\UrlRule yii\web\UrlRule, $prefix

'rules' => [
    [
        'class' => 'yii\rest\UrlRule', 
        'controller' => ['players' => 'v1/player', 'trophies' => 'v1/trophy'],
        'prefix' => 'teams/<team_id:\d+>',
    ],
],

:

/teams/1/players
/teams/1/players/2
/teams/1/trophies
/teams/1/trophies/4

, , .

0

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


All Articles