2

How is it possible to extend yii\rest\UrlRule in a way I can rewrite rules for actions of a controller? For example, I want to generate the following URIs:

/user/[username]
/user/keywords
/user/keyword/[key1]/[key2]/[...]
...

Every above actions are rendering their own view too.

Hamid Ghorashi
  • 1,003
  • 3
  • 14
  • 29

2 Answers2

0

You don't need to extend yii\rest\UrlRule. Just add your rules to routes of UrlManager by putting them on extraPatterns property of yii\rest\UrlRule.

For example suppose You defined a list action in your controller:

class BarController extends Controller
{
    public $modelClass = 'app\models\Foo';

    public function actionList()
    {
        return ['id' => 1];
    }
}

Then in configuration file add extra route:

<?php
// some configs are here
'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => [
                'v1/bar',
            ],
            'extraPatterns' => [
                'GET list' => 'list',
            ],
        ],
    ],
], 
// and some other configs are here

Now you can browse the api with /v1/bars/list. Read Yii2 Documentations for more examples.

meysam
  • 1,754
  • 2
  • 20
  • 30
  • It doesn't work for my case. Actually, I just want to beautify my URLs like rest and use the normal controller instead of ActiveController to represent output. – Hamid Ghorashi Sep 05 '16 at 11:53
  • 1
    What's your problem? `ActiveController` is extended from `Controller` and has all it parent behaviors. – meysam Sep 05 '16 at 12:18
  • 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:34
0

you must change the extends of Controller in ActiveController

class ArticleController extends ActiveController
Daniel
  • 21
  • 3