yii restful和通常路由共存

<?php

namespace app\controllers;

use Yii;
use yii\rest\ActiveController;

/**
 * 
 */
class TestController extends ActiveController
{

    public $modelClass = 'app\models\Test';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats'] = ['application/json' => yii\web\Response::FORMAT_JSON];
        return $behaviors;
    }
    
    public function actionHi($id)
    {
        return ['s', 2];
    }

}

上述代碼中行爲定義了默認返回json。php

 

'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule', 
                    'pluralize' => false,  //關閉複數顯示,如user訪問變成了users
                    'controller' => 'test'
                ],
            ],
        ],

在沒有開啓上面的配置前,/test/1,能夠經過index.php?r=test/view&id=1 訪問,也就是通常的路由規則訪問。web

沒有開啓enablePrettyUrl = true ,則經過/test/view?id=1訪問。json

若是所有按照上面示例的配置,且配置controller,則能夠直接/test/1訪問,由於這個yii\rest\UrlRule內部已經把路由作了處理。restful

如:app

[yii

'PUT,PATCH users/<id>' => 'user/update', url

'DELETE users/<id>' => 'user/delete', spa

'GET,HEAD users/<id>' => 'user/view', rest

'POST users' => 'user/create', code

'GET,HEAD users' => 'user/index',

'users/<id>' => 'user/options',

'users' =>'user/options',

]

 

在沒有開啓restful相關的配置前,按照通常的路由規則訪問。

相關文章
相關標籤/搜索