YII 2.0 API接口开发 [ 2.0 版本 ]
YII2.0 API接口开发
首先先安装 YII2.0 高级模板(安装请参考其他教程)
准备
添加数据库配置 common/config/main-local.php
![RRHLN~OMNFM(A)I)`]LP93.png](/uploads/images/201902/25232211796.png "RRHLN~OMNFM(A)I)
]LP9`3.png")
把backend目录 修改成api 修改目录下相关文件的命名空间 修改api/config/main.php下 id 和命名空间
![Q0$35OL]UQCNZ~9DQ2PGCUM.png](/uploads/images/201902/25232238902.png "Q0$35OL]UQCNZ~9DQ2PGCUM.png")
看下项目的目录结构

建立AR类 参考开发手册 (可通过 GII生成)

开始
建立 api基类
/**
- api 基类
- Created by PhpStorm.
- Author: L
- Date: 2019/1/9
- Time: 9:33
*/
namespace api\controllers;
use Yii;
use yii\filters\ContentNegotiator;
use yii\filters\VerbFilter;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\auth\QueryParamAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\CompositeAuth;
use yii\filters\Cors;
class ApiController extends ActiveController
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
QueryParamAuth::className(),
],
// 写在optional里的方法不需要token验证
'optional' => [
'login'
],
];
// 这个是跨域配置
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
// restrict access to
'Access-Control-Request-Method' => ['POST', 'GET', 'DEL'],
// Allow only POST and PUT methods
'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'],
// Allow only headers 'X-Wsse'
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
];
# 定义返回格式是:JSON
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
}
在config/ main.php-> components 里添加 response, 这串代码的用途是让 api 请求均为 200,其他 http 状态码会以 json
数据返回
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
$response->data = [
'success' => $response->isSuccessful,
'code' => $response->getStatusCode(),
'message' => $response->statusText,
'data' => $response->data,
];
$response->statusCode = 200;
},
],```
添加url美化
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false, // 是否执行严格的url解析
'suffix' => '.html', // api后缀
'rules' => [
'class'=>'yii\rest\UrlRule','controller'=>''
],
],
开启验证

如果不需要可以注释掉
如果直接访问未应许的方法 会报401错误
![[}[LJ}W(]3I9QGR1RP)M3NN.png](/uploads/images/201902/25233004899.png "[}[LJ}W(]3I9QGR1RP)M3NN.png")
添加例外之后
![QFY(5IO%Q)4]B([~7TN5BR4.png](/uploads/images/201902/25233038891.png "QFY(5IO%Q)4]B([~7TN5BR4.png")
到此 第一个api应用接口编写完成
api版本控制
在开发过程中往往会涉及到版本的更新迭代

这个就是版本的目录
准备
建立models目录
用gii去生成
![3}6`VXDH~_GJF)JAB]8ULLW.png](/uploads/images/201902/25233215926.png "3}6`VXDH~_GJF)JAB]8ULLW.png")
使用上图这个
修改api/config/main.php
0{3`NUQ8S[2)UI9)CF.png")
在控制下建立一个控制器 比如

我建立了一个测试控制器
/**
* 文件功能
* Created by PhpStorm.
* Author: L
* Date: 2019/1/9
* Time: 9:14
*/
namespace api\modules\v1\controllers;
use api\controllers\ApiController;
use api\models\Category;
use yii\filters\auth\HttpBearerAuth;
class TestController extends ApiController
{
public $modelClass='api\models\Category';
public function actionList(){
return Category::find()->select('id,category_name')->where(['isdelete'=>0])->all();
}
public function actionLogin(){
return '123';
}
}

成功
码云的地址链接直接git下来就行了
指仗走天涯
最后登录:2019-03-05
在线时长:0小时41分
- 粉丝1
- 金钱20
- 威望20
- 积分220
共 0 条评论