yii2.0 高級版 restful api使用

一、複製任意個目錄(backend)爲api
二、打開api下的main.php 修改 id=>app-api,'controllerNamespace' => 'api\controllers', 'identityClass' => 'app\models\User'(用戶認證,暫無用),'errorAction' => 'exception/errorr',(修改錯誤處)
注意:每個方法都須要在extraPatterns裏配置,也能夠設置統一匹配的模式:'<action:\w+-?\w+>' => '<action>' 該模式將匹配全部有效請求
①在components裏添加URL規則 每添加一個方法必須在此註冊
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,//嚴格模式
'showScriptName' => false,
'suffix' => '.html', // 後綴,訪問方法的後綴
'rules' => [
[
'class' => 'yii\rest\UrlRule',
//'pluralize' => false, //設置爲false 就能夠去掉複數形式了,否則訪問控制器得加上s。 注意
'controller' => 'api',
'extraPatterns' => [
// '<action:\w+-?\w+>' => '<action>',
'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;
},
],
三、打開common下的bootstrap.php 添加 Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
四、建立控制器繼承yii\rest\ActiveController。默認會有一些方法,在父類actions裏能夠看到, 不須要時繼承後直接返回空就能夠
五、定義一些行爲,自動返回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;
}
 
六、定義本身的錯誤,就是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()
],
]);
}
}
 
七、日誌設置 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
],
],
],
八、多數據庫配置 在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
}
 
九、設置session
'session' => [
'cookieParams' => ['lifetime' => 3600*24],//有效時間
],
 
十、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;
}
相關文章
相關標籤/搜索