一、添加api接口应用
1、复制粘贴一份backend/frontend应用,改名为api(可以自定义)
2、修改api文件的命名空间
3、修改config/main.php配置文件中的id => ‘app-api’
4、在common/config/bootstrap.php文件中添加api的别名Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
二、版本控制
1、yii2的版本其实就是不同的模块,操作起来相对于的比较简单,使用Yii2自带的gii即可
2、在config/main.php配置文件中配置版本对应的模块 'modules' => [ 'v1' => [ 'class' => 'api\modules\v1\Module', ], 'v2' => [ 'class' => 'api\modules\v2\Module', ], ]
三、api接口路由的配置
1、修改config/main.php配置文件中的urlManager
配置项,代码如下
'urlManager' => [
'enablePrettyUrl' => true, // 是否开启路由美化
'showScriptName' => false, // 是否显示入口脚本
'rules' => require __DIR__ . '/url-rules.php', // 路由匹配规则
'enableStrictParsing' => true // 是否开启严格解析路由模式 如果开启严格模式需要配置上面的rules
]
url-rules.php文件的内容:
$urlRuleConfig = [
[
'controller' => 'v1/default',
'extraPatterns' => [
'GET index' => 'index',
'GET list' => 'list'
]
],
[
'controller' => 'v1/user',
'extraPatterns' => [
'POST login' => 'login'
]
]
];
// 此方法主要是用来加入某些公共的配置项
// pluralize => false 将复数修改为单数的形式
// eg:pluralize => true v1/users
// eg: pluralize => false v1/user
function baseUrlRules($unit)
{
$config = [
'class' => 'yii\rest\UrlRule',
'pluralize' => false
];
return array_merge($config, $unit);
}
return array_map('baseUrlRules', $urlRuleConfig);
四、控制器/方法
1、控制器需要继承yii\rest\ActiveController
2、ActiveController默认会带有下面的几个方法,当继承了ActiveController后就完成了一个简单的CURD
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'create' => [
'class' => 'yii\rest\CreateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->createScenario,
],
'update' => [
'class' => 'yii\rest\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->updateScenario,
],
'delete' => [
'class' => 'yii\rest\DeleteAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
3、如果自带的方法不满足需求可以用下面的方法进行修改
// 继承ActiveController的控制器重写actions方法
public function actions()
{
$actions = parent::actions();
$actions['index']['class'] = 'api\modules\v1\controllers\actions\DefaultIndexAction';
$actions['list'] = [
'class' => 'api\modules\v1\controllers\actions\DefaultListAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess']
];
return $actions;
}
// 添加方法对应的请求方式
protected function verbs()
{
$verbs = parent::verbs();
$verbs['list'] = ['GET', 'HEAD'];
return $verbs;
}
4、根据需求创建自己的action,需要继承yii\rest\Action
<?php
namespace api\modules\v1\controllers\actions;
use yii\data\Pagination;
use yii\rest\Action;
class DefaultListAction extends Action
{
public function run()
{
$pageSize = \Yii::$app->request->get('pageSize', 5);
$modelClass = $this->modelClass;
$query = $modelClass::find();
$page = new Pagination([
'defaultPageSize' => $pageSize,
'totalCount' => $query->count()
]);
$dataList = $query->orderBy('id')->offset($page->offset)->limit($page->limit)->asArray()->all();
return \Yii::$app->helper->successJson('获取成功', $dataList);
}
}
五、全局异常处理
1、修改config/main.php配置文件
// 在 components配置数组中添加如下的配置项 按实际需求进行修改
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
$statusCode = $response->getStatusCode();
switch ($statusCode) {
case 500:
$data = [
'msg' => '服务器错误,请稍后再试'
];
break;
case 404:
$data = [
'msg' => '未找到资源'
];
break;
}
$data['code'] = $statusCode;
$response->data = $data;
$response->statusCode = 200;
$response->format = yii\web\Response::FORMAT_JSON;
}
]
2、封装常见的Http错误
<?php
namespace api\exceptions;
use yii\web\HttpException;
// 基础的http状态错误
class HttpExceptions extends HttpException
{
public function __construct($message = null, $code = 0, \Exception $previous = null)
{
return parent::__construct($this->statusCode, $message, $code, $previous);
}
}
<?php
// 403拒绝访问
namespace api\exceptions;
// 继承上面封装的基础类
class HttpForbiddenException extends HttpExceptions
{
public $statusCode = 403;
}