yii2 的 restful api 路由實例

yii\rest\UrlRule

使用yii\rest\UrlRule來自動映射控制器的 restful 路由,簡單快捷,缺點是必須得按規定好的方法名去寫業務。laravel

映射的規則以下,固然,你能夠修改源碼爲你的習慣:restful

public $patterns = [
    'PUT,PATCH {id}' => 'update',
    'DELETE {id}' => 'delete',
    'GET,HEAD {id}' => 'view',
    'POST' => 'create',
    'GET,HEAD' => 'index',
    '{id}' => 'options',
    '' => 'options',
];

除了被限制了HTTP動詞對應的方法名外,其餘都很好用,好比pluralize是多麼的優雅啊,能夠自動解析單詞的複數,laravel的話要一個個的去寫,反而有些不方便了yii

'urlManager'   => [
    'enablePrettyUrl'     => true,
    'showScriptName'      => false,
    'enableStrictParsing' => true,
    'rules'               => [
        [
            'class'      => 'yii\rest\UrlRule',
            'controller' => [
                'v1/user',
                'v1/news',
                'routeAlias' => 'v1/box'
            ],
            'pluralize'  => true
        ],
    ]
]

自定義路由

注意我路由裏很刻意的用了複數模式,但很雞肋,由於一些單詞的複數並非簡單的加個 s 就能夠了。post

'urlManager'   => [
    'enablePrettyUrl'     => true,
    'showScriptName'      => false,
    'enableStrictParsing' => true,
    'rules'               => [
        // 利用 module 作個版本號也是能夠的
        'GET <module:(v1|v2)>/<controller:\w+>s'                 => '<module>/<controller>/index',
        'GET <module:(v1|v2)>/<controller:\w+>s/<uid:\d+>'       => '<module>/<controller>/view',
        'POST <module:(v1|v2)>/<controller:\w+>s'                => '<module>/<controller>/create',
        'PUT,PATCH <module:(v1|v2)>/<controller:\w+>s/<uid:\d+>' => '<module>/<controller>/update',
        'DELETE <module:(v1|v2)>/<controller:\w+>s/<uid:\d+>'    => '<module>/<controller>/delete',
        'OPTIONS <module:(v1|v2)>/<controller:\w+>s'             => '<module>/<controller>/options',

        '<controller:\w+>/<action:\w+>'              => '<controller>/<action>',// normal
        '<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',// module
        '/'                                          => 'site/default',// default route
    ]
]

固然,這種高度動態的路由也能夠寫的像laravel同樣半靜態。ui

'GET v1/children'                 => 'v1/child/index',
'GET v1/children/<uid:\d+>'       => 'v1/child/view',
'POST v1/children'                => 'v1/child/create',
'PUT,PATCH v1/children/<uid:\d+>' => 'v1/child/update',
'DELETE v1/children/<uid:\d+>'    => 'v1/child/delete',
'OPTIONS v1/children'             => 'v1/child/options',

如同laravel的以下url

Route::get("/v1/children", "ChildController@index");
Route::post("/v1/children", "ChildController@create");
Route::put("/v1/children/{uid}", "ChildController@update");
Route::patch("/v1/children/{uid}", "ChildController@update");
Route::delete("/v1/children/{uid}", "ChildController@delete");
Route::options("/v1/children", "ChildController@options");
相關文章
相關標籤/搜索