欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

yii2的restful api路由实例详解

程序员文章站 2023-02-17 15:10:18
yii\rest\urlrule 使用yii\rest\urlrule来自动映射控制器的 restful 路由,简单快捷,缺点是必须得按规定好的方法名去写业务。 映...

yii\rest\urlrule

使用yii\rest\urlrule来自动映射控制器的 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的话要一个个的去写,反而有些不方便了

'urlmanager'  => [
  'enableprettyurl'   => true,
  'showscriptname'   => false,
  'enablestrictparsing' => true,
  'rules'        => [
    [
      'class'   => 'yii\rest\urlrule',
      'controller' => [
        'v1/user',
        'v1/news',
        'routealias' => 'v1/box'
      ],
      'pluralize' => true
    ],
  ]
]

自定义路由

注意我路由里很刻意的用了复数模式,但很鸡肋,因为一些单词的复数并不是简单的加个 s 就可以了。

'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一样半静态。

'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的如下

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");

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。