Yii2 基于RESTful架构的 advanced版API接口开发 配置、实现、测试,yii2restful
Yii2 基于RESTful架构的 advanced版API接口开发 配置、实现、测试,yii2restful
环境配置:
开启服务器伪静态
本处以apache为例,查看apache的conf目录下httpd.conf,找到下面的代码
1 |
|
将其前面的#去掉,如果没有找到则添加进去。
找到一下代码
1 2 3 4 5 |
|
将原本的AllowOverride None改为AllowOverride All。
然后在站点根目录下创建一个.htaccess文件,内容如下:
此处不再赘述yii2的配置,如果需要可以看YII2实战手册。
YII2实际操作:
1、配置URL规则及modules
(1)新建modules文件夹,实行api接口版本控制。例如V1版本、V2版本……
在v1文件夹下新建controllers文件夹(控制器)、models文件夹(模型)、Module.php配置文件。
Module.php文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
第2行和第7行随版本扩展而变化(v1->v2...)。
(2)配置config文件夹下的main.php文件
1 php 2 $params = array_merge(require (__DIR__ . '/../../common/config/params.php'), require (__DIR__ . '/../../common/config/params-local.php'), require (__DIR__ . '/params.php'), require (__DIR__ . '/params-local.php')); 3 4 return [ 5 'id' => 'app-api', 6 'basePath' => dirname(__DIR__), 7 'bootstrap' => [ 8 'log' 9 ], 10 'modules' => [ 11 'v1' => [ 12 'class' => 'api\modules\v1\Module' 13 ], 14 'v2' => [ 15 'class' => 'api\modules\v2\Module' 16 ] 17 ], 18 'controllerNamespace' => 'api\controllers', 19 'components' => [ 20 'user' => [ 21 'identityClass' => 'common\models\User', 22 'enableAutoLogin' => false, 23 'enableSession' => false, 24 'loginUrl' => null 25 ], 26 'urlManager' => [ 27 'enablePrettyUrl' => true, // 启用美化URL 28 'enableStrictParsing' => true, // 是否执行严格的url解析 29 'showScriptName' => false, // 在URL路径中是否显示脚本入口文件 30 'rules' => [ 31 [ 32 'class' => 'yii\rest\UrlRule', 33 'controller' => [ 34 'v1/site' 35 ] 36 ], 37 [ 38 'class' => 'yii\rest\UrlRule', 39 'controller' => [ 40 'v2/site' 41 ] 42 ] 43 ] 44 ], 45 'log' => [ 46 'traceLevel' => YII_DEBUG ? 3 : 0, 47 'targets' => [ 48 [ 49 'class' => 'yii\log\FileTarget', 50 'levels' => [ 51 'error', 52 'warning' 53 ] 54 ] 55 ] 56 ], 57 'errorHandler' => [ 58 'errorAction' => 'site/error' 59 ] 60 ], 61 'params' => $params 62 ]; main.php注意10~17行、20~44行的组件配置,相信大家仔细阅读就能明白,此处不再赘述原理,请大家尤其注意33~35行的代码,此处表示的是v1/site控制器,随着接口控制器的增多,可以直接在数组中增加即可。本文力求快速配置出RESTful架构的实现。
(3)v2、v3表示以后的版本变化,配置都类似于v1文件夹。
2、创建一个模型
数据库准备一个名为mxq_guide的数据表
1 2 3 |
|
创建后请注意及时往数据库添加几条数据信息。
通过脚手架gii来创建guide.php模型(使用方法请看yii2权威指南)。生成后的文件注意改写,修改为如下形式以满足RESTful的需求。之后从models文件夹中转移到v1/models文件夹中,并注意命名空间的修改。
1 php 2 namespace api\modules\v1\models; 3 4 use Yii; 5 use yii\db\ActiveRecord; 6 use yii\web\IdentityInterface; 7 8 /** 9 * This is the model class for table "{{%guide}}". 10 * 11 * @property integer $id 12 * @property string $imgurl 13 * @property integer $status 14 * @property integer $flag 15 */ 16 class Guide extends ActiveRecord implements IdentityInterface 17 { 18 19 public static function findIdentityByAccessToken($token, $type = null) 20 { 21 return static::findOne([ 22 'access_token' => $token 23 ]); 24 } 25 26 public function getId() 27 { 28 return $this->id; 29 } 30 31 public function getAuthKey() 32 { 33 return $this->authKey; 34 } 35 36 public function validateAuthKey($authKey) 37 { 38 return $this->authKey === $authKey; 39 } 40 41 public static function findIdentity($id) 42 { 43 return static::findOne($id); 44 } 45 46 public static function tableName() 47 { 48 return '{{%guide}}'; 49 } 50 51 public function rules() 52 { 53 return [ 54 [ 55 [ 56 'imgurl', 57 'status', 58 'flag' 59 ], 60 'required' 61 ], 62 [ 63 [ 64 'status', 65 'flag' 66 ], 67 'integer' 68 ], 69 [ 70 [ 71 'imgurl' 72 ], 73 'string', 74 'max' => 255 75 ] 76 ]; 77 } 78 79 public function attributeLabels() 80 { 81 return [ 82 'id' => Yii::t('app', 'ID'), 83 'imgurl' => Yii::t('app', 'imgurl'), 84 'status' => Yii::t('app', 'status'), 85 'flag' => Yii::t('app', 'flag') 86 ]; 87 } 88 } guide.php3、创建一个控制器
1 php 2 namespace api\modules\v1\controllers; 3 4 use Yii; 5 use yii\rest\ActiveController; 6 use yii\filters\auth\CompositeAuth; 7 use yii\filters\auth\QueryParamAuth; 8 use yii\data\ActiveDataProvider; 9 10 class SiteController extends ActiveController 11 { 12 13 public $modelClass = 'api\modules\v1\models\guide'; 14 15 public $serializer = [ 16 'class' => 'yii\rest\Serializer', 17 'collectionEnvelope' => 'items' 18 ]; 19 20 // public function behaviors() 21 // { 22 // $behaviors = parent::behaviors(); 23 // $behaviors['authenticator'] = [ 24 // 'class' => CompositeAuth::className(), 25 // 'authMethods' => [ 26 // QueryParamAuth::className() 27 // ] 28 // ]; 29 // return $behaviors; 30 // } 31 public function actions() 32 { 33 $actions = parent::actions(); 34 // 注销系统自带的实现方法 35 unset($actions['index'], $actions['update'], $actions['create'], $actions['delete'], $actions['view']); 36 return $actions; 37 } 38 39 public function actionIndex() 40 { 41 $modelClass = $this->modelClass; 42 $query = $modelClass::find(); 43 return new ActiveDataProvider([ 44 'query' => $query 45 ]); 46 } 47 48 public function actionCreate() 49 { 50 $model = new $this->modelClass(); 51 // $model->load(Yii::$app->getRequest() 52 // ->getBodyParams(), ''); 53 $model->attributes = Yii::$app->request->post(); 54 if (! $model->save()) { 55 return array_values($model->getFirstErrors())[0]; 56 } 57 return $model; 58 } 59 60 public function actionUpdate($id) 61 { 62 $model = $this->findModel($id); 63 $model->attributes = Yii::$app->request->post(); 64 if (! $model->save()) { 65 return array_values($model->getFirstErrors())[0]; 66 } 67 return $model; 68 } 69 70 public function actionDelete($id) 71 { 72 return $this->findModel($id)->delete(); 73 } 74 75 public function actionView($id) 76 { 77 return $this->findModel($id); 78 } 79 80 protected function findModel($id) 81 { 82 $modelClass = $this->modelClass; 83 if (($model = $modelClass::findOne($id)) !== null) { 84 return $model; 85 } else { 86 throw new NotFoundHttpException('The requested page does not exist.'); 87 } 88 } 89 90 public function checkAccess($action, $model = null, $params = []) 91 { 92 // 检查用户能否访问 $action 和 $model 93 // 访问被拒绝应抛出ForbiddenHttpException 94 // var_dump($params);exit; 95 } 96 } SiteController.php控制器请创建在modules/controllers文件夹下,并注意命名空间的修改。
要注意的是,此处的控制器与普通的控制器继承Controller不同,此处需继承ActiveController类。
20~30行注释的代码是基于RESTful架构的access_token认证,目前还未测试通过,后续补充。
至此,基于YII2的所有配置已基本完成,接下来介绍api接口测试工具及方法。
RESTful的测试工具PostMAN:
首先介绍一下postman这款插件,是基于谷歌浏览器的一款模拟请求的实用插件。具体使用,在下面测试过程中涉及截图,介绍不足之处请见谅,自己也是第一次使用。
推荐使用上面的APP版本,便于后续封装自己写好的api接口,下面的是网页版本。
YII2支持的RESTful有四种请求方式:GET查看信息,POST创建信息,PUT更新信息,DELETE删除信息。
下面开始演示四种请求数据的方式。(只是截图演示效果,具体使用还需要大家自己去摸索。)
此处演示的是GET方法请求数据库的数据。对应的是modules/controllers/SiteController/actionIndex方法。
请大家注意最上面方框内的URL地址,rest默认将控制器进行复数请求http://api.mxq.com/v1/sites,此处就是rest的默认规则。
打*星号位置显示的是正常的效果,如若出现错误,大家可以去YII权威指南——错误检查错误原因。
YII2的ActiveController默认实现了数据的分页效果。
此处演示的是POST方法新建数据库的数据。对应的是modules/controllers/SiteController/actionCreate方法。
如果在数据库的数据层写好数据校验规则,此处提交数据不满足要求的时候就会显示相应的错误。这也是REST的优势之一。比如如下情况,flag我定义的是int型:
接下来演示的是PUT方法更新数据库的数据。对应的是modules/controllers/SiteController/actionUpdate方法。
此处请大家再次注意最上面的URL:http://api.mxq.com/v1/sites/15 此处15代表的是数据库id为15的数据,表示更新数据库ID为15的数据信息。请大家一定注意。RESTful在使用更新和删除数据操作的时候,id不能一表单的形式提交,必须紧跟在URL之后。
接下来演示的是DELETE方法删除数据库的数据。对应的是modules/controllers/SiteController/actionDelete方法。
当返回值为1的时候表示的就是删除操作执行成功。具体原理请大家仔细观察sitecontroller控制器内的函数。
以上就是基于yii2的RESTful的一些简单介绍、实现方法以及测试结果。有什么不正确或遗漏的地方,欢迎大家来补充。后续也会在此基础上进行更新。本人第一次接触yii2框架和RESTful架构,表述如有不对之处,请大家见谅。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Flask-RESTful and Swagger: Best Practices for Building RESTful APIs in Python Web Applications (Part 2) In the previous article, we explored the best practices for building RESTful APIs using Flask-RESTful and Swagger. We introduced the basics of the Flask-RESTful framework and showed how to use Swagger to build documentation for a RESTful API. Book

RESTful API Development with Laravel: Building Modern Web Services With the rapid development of the Internet, the demand for Web services is increasing day by day. As a modern Web service architecture, RESTfulAPI is lightweight, flexible, and easy to expand, so it has been widely used in Web development. In this article, we will introduce how to use the Laravel framework to build a modern RESTful API. Laravel is a PHP language

Django is a web framework that makes it easy to build RESTful APIs. RESTfulAPI is a web-based architecture that can be accessed through HTTP protocol. In this article, we will introduce how to use Django to build RESTful APIs, including how to use the DjangoREST framework to simplify the development process. Install Django First, we need to install Django locally. You can use pip to install Django, specifically

1. Overview of RESTful REST (RepresentationalStateTransfer) style is a resource-oriented Web application design style that follows some design principles to make Web applications have good readability, scalability, and maintainability. Let's explain each aspect of the RESTful style in detail: Resource identifier: In the RESTful style, each resource has a unique identifier, usually a URL (UniformResourceLocator). URLs are used to identify the location of resources so that clients can access them using the HTTP protocol. For example, a simple URL could be: http

With the development and popularity of the Internet, web applications and mobile applications are becoming more and more common. These applications need to communicate with the backend server and get or submit data. In the past, the conventional way to communicate was to use SOAP (Simple Object Access Protocol) or XML-RPC (XML Remote Procedure Call). Over time, however, these protocols were deemed too cumbersome and complex. Modern applications require more lightweight and straightforward APIs to communicate. RESTfulAPI (presentation layer state conversion AP

In the current environment of continuous innovation in information technology, RESTful architecture is popular in various commonly used WebAPI applications and has become an emerging service development trend. The Beego framework, as a high-performance and easily scalable Web framework in Golang, is widely used in the development of RESTful services due to its advantages of efficiency, ease of use, and flexibility. The following will provide some reference for developers from the perspective of best practices for developing RESTful services in Beego. 1. Routing design in REST

How to use Java to develop a RESTful-based API. RESTful is an architectural style based on the HTTP protocol. It uses the GET, POST, PUT, DELETE and other methods of the HTTP protocol to operate resources. In Java development, some frameworks can be used to simplify the development process of RESTful API, such as SpringMVC, Jersey, etc. This article will introduce you in detail how to use Java to develop a RESTful-based

RESTfulAPI is a commonly used API design style in the current Web architecture. Its design concept is based on the standard method of the HTTP protocol to complete the representation and interaction of Web resources. During the implementation process, RESTful API follows a series of rules and constraints, including cacheability, server-client separation, statelessness, etc. These rules ensure the maintainability, scalability, security and ease of use of the API. Next, this article will introduce in detail the design and implementation of RESTfulAPI
