yii2.0 高级版 restful api使用

1、复制任意个目录(backend)为api
2、打开api下的main.php 修改 id=>app-api,'controllerNamespace' => 'api\controllers', 'identityClass' => 'app\models\User'(用户认证,暂无用),'errorAction' => 'exception/errorr',(修改错误处)
①在components里添加URL规则 每添加一个方法必须在此注册
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,//严格模式
'showScriptName' => false,
'suffix' => '.html', // 后缀,访问方法的后缀
'rules' => [
[
'class' => 'yii\rest\UrlRule',
//'pluralize' => false, //设置为false 就可以去掉复数形式了,不然访问控制器得加上s。 注意
'controller' => 'api',
'extraPatterns' => [
'GET index' => 'index',
'POST,GET test' => 'test'
]
],
],
],
②自定义返回200,具体格式自己调试 主要有正常返回数据,手动抛出异常、系统异常
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if (isset($response->data['message'])){
$response->data = [
// 'success' => $response->isSuccessful,
'code' => isset($response->data['code'])?$response->data['code']:500,
// 'message' => $response->statusText,
'info' => isset($response->data['message'])?$response->data['message']:'app error',
];
 
}
 
$response->statusCode = 200;
},
],
3、打开common下的bootstrap.php 添加 Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
4、创建控制器继承yii\rest\ActiveController。默认会有一些方法,在父类actions里可以看到, 不需要时继承后直接返回空就可以
5、定义一些行为,自动返回json、跨域等。 用户登录我们是用的redis,所以认证没整太明白
public function behaviors()
{
$behaviors = parent::behaviors();
// $behaviors['authenticator'] = [
// 'class' => CompositeAuth::className(),
// 'authMethods' =>
// [
// # 下面是三种验证access_token方式
// //HttpBasicAuth::className(),
// //HttpBearerAuth::className(),
// //这是GET参数验证的方式 # http://10.10.10.252:600/user/index/index?access-token=xxxxxxxxxxxxxxxxxxxx
// QueryParamAuth::className(),
// ],
// // 写在optional里的方法不需要token验证
// 'optional' => [],
// ];
 
// 这个是跨域配置
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['POST', 'GET', 'DEL'],
'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'],
'Access-Control-Allow-Origin' => ['*'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
];
#定义返回格式是:JSON
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
 
6、定义自己的错误,就是errorAction配置的方法
class ExceptionController extends \yii\web\Controller
{
 
//错误处理
public function actionError()
{
$exception = \Yii::$app->errorHandler->exception;
$code = $exception->statusCode ? $exception->statusCode : $exception->getCode();
//CommonController::response( $code ? $code : 400,$exception->getMessage());
 
return \Yii::createObject([
'class' => 'yii\web\Response',
'format' => \yii\web\Response::FORMAT_JSON,
'data' => [
'code' => $code,
'info' => $exception->getMessage()
],
]);
}
}
 
7、日志设置 main 下面的components里log。可以设置多个。
在控制器里主要通过设置属性来开启关闭
\Yii::$app->log->targets['frontend']->enabled = true;
\Yii::$app->log->targets['admin']->enabled = true;
\Yii::warning($result,'frontend'); 该方法将手动写入日志
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'flushInterval' => 1,
'targets' => [
'frontend' => [
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'exportInterval' => 1,
'logFile' => '../logs/frontend/'.date('Ymd').'.log',
'logVars' => ['_POST','_GET'], //捕获请求参数
'fileMode' => 0775, //设置日志文件权限
'rotateByCopy' => false, //是否以复制的方式rotate
'prefix' => function() { //日志格式自定义 回调方法
if (Yii::$app === null) {
return '';
}
$controller = Yii::$app->controller->id;
$action = Yii::$app->controller->action->id;
return "[$controller-$action]\n";
},
],
'admin' => [
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning','info'],
'exportInterval' => 1,
'logFile' => '../logs/admin/'.date('Ymd').'.log',
'logVars' => ['_POST','_GET'], //捕获请求参数
'fileMode' => 0775, //设置日志文件权限
'rotateByCopy' => false, //是否以复制的方式rotate
],
],
],
8、多数据库配置 在components 里添加配置 默认的id 为db
①添加三个配置
$db = require(__DIR__ . '/db.php');
'normal_ios' => $db['normal_ios'],
'normal_android' => $db['normal_android'],
'normal_web' => $db['normal_web'],
②使用的时候指定一个
\Yii::$app->normal_ios
\Yii::$app->normal_android
\Yii::$app->normal_web
$this->find()->where($where)->one(\Yii::$app->normal_ios);
\Yii::$app->normal_ios->createCommand() ->update($tab,$date,$where)->execute();
③在视图里使用model模型的时候需要注意 重写getDb方法,不然取字段生成表单的时候会报错找不到哪个db
//防止构建表单是出错
public static function getDb()
{
return \Yii::$app->normal_web
}
 
9、设置session
'session' => [
'cookieParams' => ['lifetime' => 3600*24],//有效时间
],
 
10、nginx配置URL支持pathinfo
location ~ \.php$ { #去掉$
root E:/phpStudy/WWW/tp/public/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$; #增加这一句
fastcgi_param PATH_INFO $fastcgi_path_info; #增加这一句
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

猜你喜欢

转载自www.cnblogs.com/fwqblogs/p/10132792.html
今日推荐