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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
What's your problem? ActiveController is extended from Controller and has all it parent behaviors.
0

you must change the extends of Controller in ActiveController

class ArticleController extends ActiveController

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.