0

I have disabled the default pluralization of my REST rules by setting yii\rest\UrlRule->pluralize = false and now my UserController is accessible via:

  • GET user/<id> -- returns the details of a user by its ID
  • GET user - returns a list of all users
  • POST user -- create a new user

I want to have second (and only this one) rule to be pluralized, so GET users returns a list of all users while GET user/<id> returns the details of a user. How can I achieve this?

I've tried the following:

'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'user',
        'pluralize' => false,
         'extraPatterns' => [
              'GET users' => 'user',
         ],
    ],

But this doesn't work. The user/2 returns given user, the user return all users, but users ends up with 404.

trejder
  • 17,148
  • 27
  • 124
  • 216

1 Answers1

0

Yes, it is possible, but you have to use two rules to define such thing:

'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'user',
        'pluralize' => false,
         'except' => ['index'],
    ],
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'user',
         'patterns' => [
              'GET,HEAD' => 'index',
         ],
    ],

This will allow you to work on a single record using singular routes (i.e. GET /user/7, DELETE /user/3) and list all records using plural route (i.e. GET users). Details in the source.

trejder
  • 17,148
  • 27
  • 124
  • 216