侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Yii2中Restful API原理实例分析

框架(架构)  /  管理员 发布于 7年前   316

本文实例分析了Yii2中Restful API原理。分享给大家供大家参考,具体如下:

Yii2 有个很重要的特性是对 Restful API的默认支持, 通过短短的几个配置就可以实现简单的对现有Model的RESTful API

这里通过分析rest部分源码,简单剖析下yii2 实现 restful 的原理,并通过一些定制实现 对 关联模型的RESTful api 操作。

~ 代表 extends from 的关系

| | rest/
| | |-Action.php ~ `\yii\base\Action`
| | |-Controller.php ~  `\yii\web\Controller`
| | | |-ActiveController.php ~ `rest\Controller`
| | |-Serializer.php ~ `yii\base\Component`
| | |-UrlRule.php ~ `yii\web\CompositeUrlRule`
| | |-CreateAction.php ~ `rest\Action`
| | |-DeleteAction.php ~ `rest\Action`
| | |-IndexAction.php ~ `rest\Action`
| | |-OptionsAction.php ~ `rest\Action`
| | |-UpdateAction.php ~ `rest\Action`
| | |-ViewAction.php ~ `rest\Action`

1. rest/Controller ~ \yii\web\Controller

Controller是 RESTful API 控制器类的基类

它在一个API请求的控制周期中一次实现了下面的步骤 1~5:

① 解析响应的内容格式
② 校验请求方法
③ 检验用户权限
④ 限制速度
⑤ 格式化响应数据

use yii\filters\auth\CompositeAuth;use yii\filters\ContentNegotiator;use yii\filters\RateLimiter;use yii\web\Response;use yii\filters\VerbFilter;/** * Controller is the base class for RESTful API controller classes. * * Controller implements the following steps in a RESTful API request handling cycle * 1. Resolving response format (see [[ContentNegotiator]]); * 2. Validating request method (see [[verbs()]]). * 3. Authenticating user (see [[\yii\filters\auth\AuthInterface]]); * 4. Rate limiting (see [[RateLimiter]]); * 5. Formatting response data (see [[serializeData()]])behaviors  contentNegotiator  verbFilter  authenticator  rateLimiterafterAction  serializeData Yii::createObject($this->serializer)->serialize($data)verbs []*/class Controller extends \yii\web\Controller{  public $serializer = 'yii\rest\Serializer';  public $enableCsrfValidation = false;  public function behaviors()  {    return [      'contentNegotiator' => [        'class' => ContentNegotiator::className(),        'formats' => [          'application/json' => Response::FORMAT_JSON,          'application/xml' => Response::FORMAT_XML,        ],      ],      'verbFilter' => [        'class' => VerbFilter::className(),        'actions' => $this->verbs(),      ],      'authenticator' => [        'class' => CompositeAuth::className(),      ],      'rateLimiter' => [        'class' => RateLimiter::className(),      ],    ]  }  public function verbs()  {    return [];  }  public function serializeData($data)  {    return Yii::createObject($this->serializer)->serialize($data);  }  public function afterAction($action, $result)  {    $result = parent::afterAction($action, $result);    return $this->serializeData($result);  }}

2. rest/ActiveController ~ rest/Controller

ActiveController 实现了一系列的和 ActiveRecord 互通数据的RESTful方法

ActiveRecord 的类名由 modelClass 变量指明, yii\db\ActiveRecordInterface ???

默认的, 支持下面的方法:

 * - `index`: list of models
 * - `view`: return the details of a model
 * - `create`: create a new model
 * - `update`: update an existing model
 * - `delete`: delete an existing model
 * - `options`: return the allowed HTTP methods

可以通过覆盖 actions() 并且 unsetting 响应的 action 来禁用这些默认的动作。

要增加一个新的动作, 覆盖 actions() 向其末尾增加一个新的 action class 或者 是一个新的 action method

注意一点,确保你同时也覆盖了 verbs() 方法来声明这个新的动作支持那些HTTP Method

也需要覆盖checkAccess() 来检查当前用户是否有权限来执行响应的某个动作。

根据上面的说明再写一遍 Controller

class ActiveController extends Controller{  public #modelClass;  public $updateScenario = Model::SCENARIO_DEFAULT;  public $createScenario = Model::SCENARIO_DEFAULT;  public function init()  {    parent::init();    if($this->modelClass == null){      throw new InvalidConfigException('The "modelClass" property must be set.');    }  }  public function actions()  {    return [      'index' => [        'class' => 'app\controllers\rest\IndexAction',        'modelClass' => $this->modelClass,        'checkAccess' => [$this, 'checkAccess'],      ],      'view'...      'create'...      'update'...      'delete'...      'options'...    ];  }  protected function verbs()  {    return [      'index' => ['GET', 'HEAD'],      'view' =>['GET', 'HEAD'],      'create' =>['POST'],      'update' =>['PUT', 'PATCH'],      'delete' =>['DELETE'],    ];  }  public function checkAccess($action, $model=null, $params = [])  {  }}

下面来实现一个继承自 这个rest\ActiveController的 News 控制器:

namespace app\controllers;use app\controllers\rest\ActiveController; #刚才这个AC,我从yii/rest下面拷贝了一份出来class NewsController extends ActiveController{  public $modelClass ='app\models\News';}

定义到这里就足够实现 rest\ActiveController 里面的默认方法了
下面来覆盖下,实现一些定制的方法

class NewsController extends ActiveController{  public $modelClass = 'app\models\News';  #定制serializer  #public $serializer = 'yii\rest\Serializer';  public $serializer = [    'class' => 'app\controllers\rest\Serializer',    'collectionEnvelope' => 'items',  ];  public function behaviors()  {    $be = ArrayHelper::merge(      parent::behaviors(),      [        'verbFilter' => [          'class' => VerbFilter::className(),          'actions' => ['index' => ['get'],...          ]        ],        'authenticator' => [          'class' => CompositeAuth::className(),          'authMethods' => [HttpBasicAuth::className(),HttpBearerAuth::className(),QueryParamAuth::className(),          ]        ],        'contentNegotiator' => [          'class' => ContentNegotiator::className(),          'formats' => ['text/html' => Response::FORMAT_HTML,          ]        ],        'access' => [          'class' => AccessControl::className(),          'only' => ['view'],          'rules' => [[ 'actions' => ['view'], 'allow' => false, 'roles' => ['@'],],         ],        ]      ],    );    return $be;  }  public function checkAccess()  {  }}

3. 定制Actions

如果要对 Actions 进行大的改动,建议拷贝一份出来,不要使用原始的 yii\rest\XXXAction命名空间

我这里以要实现对related models进行 CURD 操作为目标进行大的改动

Action

在定制各个action之前, 先看看它们的基类 rest\Action, 主要是一个 findModel的方法

class Action extend \yii\base\Action{  public $modelClass;  public $findModel;  public $checkAccess;  public function init()  {    if($this->modelClass == null) {      throw new InvalidConfigException(get_class($this). '::$modelClass must be set');    }  }  public function findModel($id)  {    if($this->findModel !== null) {      return call_user_func($this->findModel, $id, $this);    }    $modelClass = $this->modelClass;    $keys = $modelClass::primaryKey();    if(count($keys) > 1) {      $values = explode(',', $id);      if..    } elseif($id !== null) {      $model = $modelClass::findOne($id);    }    if(isset($model)){      return $model;    }else {      throw new NotFoundHttpException("Object not found: $id");    }  }}

view

view 动作不需要改动,因为 model 有 getRelated 的自有机制

class ViewAction extend Action{  public function run($id)  {    $model = $this->findModel($id);    if($this->checkAccess) {      call_user_func($this->checkAccess, $this->id, $model);    }  }}

update

public function run($id){  /* @var $model ActiveRecord */  $model = $this->findModel($id);  if ($this->checkAccess) {   call_user_func($this->checkAccess, $this->id, $model);  }  $model->scenario = $this->scenario;  $model->load(Yii::$app->getRequest()->getBodyParams(), '');  $model->save();  return $model;}

经过改造后,需要满足对关联模型的update动作

public function run($id){  /* @var $model ActiveRecord */  $model = $this->findModel($id);  if ($this->checkAccess) {   call_user_func($this->checkAccess, $this->id, $model);  }  $model->scenario = $this->scenario;    /*     *     * x-www-form-urlencoded key=>value     * image mmmmmmmm     * link nnnnnnnnnn     * newsItem[title]=>ttttttttttt , don't use newsItem["title"]     * newsItem[body]=>bbbbbbbbbbb     * don't use newsItem=>array("title":"tttttt","body":"bbbbbbb")     * don't use newsItem=>{"title":"ttttttt","body":"bbbbbbbb"}     *     */    $newsItem = Yii::$app->getRequest()->getBodyParams()['newsItem'];    /*      Array      (        [title] => ttttttttttt        [body] => bbbbbbbbbbb      )     */    $model->newsItem->load($newsItem, '');    #$model->newsItem->load(Yii::$app->getRequest()->getBodyParams(), '');    #print_R($model->newsItem);exit;    #print_R($model->newsItem);exit;    if($model->save())    {      $model->load(Yii::$app->getRequest()->getBodyParams(), '');      $model->newsItem->save();    }  return $model;}

这里还应该对 newsItem save 失败 的情况进行处理,暂且不处理。

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • Yii2 RESTful中api的使用及开发实例详解
  • Yii2框架RESTful API 格式化响应,授权认证和速率限制三部分详解
  • Yii2框架制作RESTful风格的API快速入门教程
  • yii2项目实战之restful api授权验证详解


  • 上一条:
    Yii中的cookie的发送和读取
    下一条:
    Yii2中设置与获取别名的函数(setAlias和getAlias)用法分析
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客