1、复制任意个目录(backend)为api
2、打开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;
},
],
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;
}
- Yii2.0 高级版安装 windows
最近在学习yii2.0 在安装高级版的时候遇到一些问题 索性解决了 下面分享一下 一.关于下载 自行百度,在Yii Framework 中文社区 下载专区下载高级应用程序模板(这边下载用电信网络不用下 ...
- Yii2.0 高级版修改默认访问控制器
frontend->config->main-local.php $config = [ 'defaultRoute' => 'index/index',//修改默认访问控制器 'c ...
- Yii2.0高级框架数据库增删改查的一些操作(转)
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- Yii2.0高级框架数据库增删改查的一些操作
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- yii2.0高级框架配置时打开init.bat秒退的解决方法 (两种方法)
第一种: 这几天刚接触到yii2.0框架,在配置advanced版本时运行init.bat初始化文件时老是闪退: 用cmd运行该文件时显示:The OpenSSL PHP extension is r ...
- [YII2.0] 高级模板简单安装教程
YIICHINA官网教程就很完善:http://www.yiichina.com/tutorial/692 但是在yii2框架安装运行init.bat报错php.exe不是内部或外部命令, 解决办法: ...
- yii2.0-advanced 高级版项目搭建
(一) 原文地址:http://www.yii-china.com/post/detail/1.html (二) 原文地址:http://www.yii-china.com/post/detail/2 ...
- Yii2.0 高级模版编写使用自定义组件(component)
翻译自:http://www.yiiframework.com/wiki/760/yii-2-0-write-use-a-custom-component-in-yii2-0-advanced-tem ...
- 使用 Spring Boot 2.0 + WebFlux 实现 RESTful API
概述 什么是 Spring WebFlux, 它是一种异步的, 非阻塞的, 支持背压(Back pressure)机制的Web 开发框架. 要深入了解 Spring WebFlux, 首先要了知道 R ...
随机推荐
- React 常用插件库
js 加密 crypto-js (des加密,md5) crypto-js https://www.npmjs.com/package/crypto-js Mock联调 数据是前端开发过程中必不可少的 ...
- 20145307第七周JAVA学习报告
20145307<Java程序设计>第七周学习总结 教材学习内容总结 Lambda Lambda语法概述: Arrays的sort()方法可以用来排序,在使用sort()时,需要操作jav ...
- 20145335郝昊《java程序设计》第7周学习总结
20145335郝昊 <Java程序设计>第7周学习总结 教材学习内容总结 认识时间与日期 格林威治标准时间:简称GMT时间,参考格林威治皇家天文台的标准太阳时间. 世界时:简称UT,借由 ...
- 20145335郝昊《java程序设计》第5周学习总结
20145335郝昊<Java程序设计>第5周学习总结 教材学习内容总结 第八章 语法与继承架构 使用try.catch 特点: - 使用try.catch语法,JVM会尝试执行try区块 ...
- close与shutdown系统调用
使用多线程时,pthread_create的参数flag有CLONE_FILES, 最终调用do_fork(),并且会根据CLONE_FILES标志来调用copy_files()来共享父进程中的文件描 ...
- .net 下的 HttpRuntime.Cache 应用
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using Syste ...
- Interleaving String,交叉字符串,动态规划
问题描述: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Give ...
- 通过spring整合activeMQ实现jms实例
写的很详细 http://blog.csdn.net/leonardo9029/article/details/43154385
- [eclipse]Syntax error on tokens, delete these tokens问题解决
错误:Syntax error on tokens, delete these tokens 出现这样的错误一般是括号.中英文字符.中英文标点.代码前面的空格,尤其是复制粘贴的代码,去掉即可. 如下图 ...
- Kinect研究文档
1. Kinect主要脚本介绍 1.1 KinectManager脚本 控制传感器并轮询数据流, 下图是参数详解: 公共API网址:https://ratemt.com/k2gpapi/annot ...