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 ...
随机推荐
- 20145310第一周JAVA实验报告
20145310第一周JAVA实验报告 实验内容 1.使用JDK编译.运行简单的Java程序: 2.使用Eclipse 编辑.编译.运行.调试Java程序. 实验要求 使用JDK和IDE编译.运行简单 ...
- 实现在vista和win7中使用管理员权限接收WM_DROPFILES(OnDropFiles())消息的方法(好像XP不支持这个函数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #pragma once #ifndef WM_COPYGLOBALD ...
- VMware 共享目录不显示的解决办法
centos mount -t vmhgfs .host:/ /mnt/hgfs # 如果有如下提示: # Error: cannot mount filesystem: No such device ...
- cogs 539. 牛棚的灯
★★☆ 输入文件:lights.in 输出文件:lights.out 简单对比 时间限制:1 s 内存限制:128 MB [问题描述] 贝希和她的闺密们在她们的牛棚中玩游戏.但是天不从 ...
- 如何为openwrt中的某个模块生成PKG_MIRROR_HASH
答:介绍两种方法,第一种自动生成(当然使用自动的啦),第二种手动生成 第一种方法: 1.在软件包的Makefile中让此项写成这样PKG_MIRROR_HASH:=skip (如果不加上skip,那 ...
- git gc内存错误的解决方案
Auto packing the repository for optimum performance. You may alsorun "git gc" manually. Se ...
- MySQL 删除重复记录
==========A really easy way to do this is to add a UNIQUE index on the 3 columns. When you write the ...
- LeetCode——Sort List
Question Sort a linked list in O(n log n) time using constant space complexity. Solution 分析,时间复杂度要求为 ...
- webservice的cxf和spring整合发布
1.新建一个web项目 2.导入cxf相应的jar包,并部署到项目中 3.服务接口 package com.xiaostudy; /** * @desc 服务器接口 * @author xiaostu ...
- Python学习札记(十九) 高级特性5 迭代器
参考:迭代器 Note 1.可用于for循环的对象有两类:(1)集合数据类型:list tuple dict str set (2)Generator:生成器和含yield语句的函数.这些可以直接作用 ...