0

I have created a standard yii\rest\ActiveController and added my custom action to it:

public function actionTest($id)
{
    return ['test' => $id];
}

To make it work, I have added a new entry to extraPatterns of rules of yii\web\UrlManager:

'extraPatterns' => [
    'GET test/{id}' => 'test',
],

Tested, all OK. Then I wanted to support POST verb for this route, so I added another entry:

'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'user',
        'pluralize' => false,
        'except' => ['index'],
        'extraPatterns' => [
            'GET test/{id}' => 'test',
            'POST test/{id}' => 'test',
        ],
    ],

Then DELETE and so on. And... there must be something that I am doing really wrong, because for:

  • Six methods: POST, GET, PUT, PATCH, OPTIONS and DELETE per each custom action
  • Five different actions per each controller and
  • Seven REST controllers

I'll end up with my main configuration file growing to... 6 * 5 * 7 = 210 lines?

So, what is in Yii 2 the best / the most reliable way of making sure that every custom action in every REST controller will be accessible for every method / verb and not making this by growing configuration file by hundreds of lines?

trejder
  • 17,148
  • 27
  • 124
  • 216
  • If you are going to route every verb into same action than you should probably use [`yii\web\UrlRule`](https://www.yiiframework.com/doc/api/2.0/yii-web-urlrule) instead of `yii\rest\UrlRule`. The rest version of `UrlRule` expects that each verb will be handled by different action and it has default patterns for most commonly used verb <=> action pairing. – Michal Hynčica Jun 14 '22 at 14:40
  • I'll be routing every verb to corresponding action, as it is currently done in yii\rest\ActiveController. So your comment seems to be confirming that there is no other way, I am doing this correctly and for a lot of REST controllers and actions, I'll have a gigantic configuration file. Madness. – trejder Jun 15 '22 at 14:04
  • then why don't you put those extra actions into separate controller as create/view/update/delete/options actions to make use of default patterns? Or you can make your own implementation of `yii\web\UrlRuleInterface` from scratch or by extending `yii\rest\UrlRule`. Another option might be use of [`yii\web\UrlManager::$ruleConfig`](https://www.yiiframework.com/doc/api/2.0/yii-web-urlmanager#$ruleConfig-detail) to set default value for `extraPatterns` property of each rule. But it's hard to say what will be the best way if we know nothing about the actions you are going to use. – Michal Hynčica Jun 15 '22 at 14:57
  • Or you can simply use some `foreach` cycle to generate the array of rules dynamically. It's just an array of some values anyway. – Michal Hynčica Jun 15 '22 at 15:04
  • Hi how can I add date token? I have also posted a [question](https://stackoverflow.com/q/73578796/6854117). Can you pl check it? – Moeez Sep 02 '22 at 07:35

0 Answers0