Give it some time, everything will be okay. — 《那些年我们疯狂的青春/青春洋溢色彩/This Youth is Crazy》
4.3.1 模拟的业务场景
假设我们需要为“奔跑吧兄弟”综艺节目开发一套手机App的投票接口,以供用户在观看电视的同时,可以进行投票活动参与互动。
下面将以此模拟的业务场景,提供一个接口开发实战的过程。
4.3.2 源代码下载
4.3.3 接口总列表
以下是我们根据业务需求整理出来的接口:
- 1、用户可以通过微信、QQ、新浪微博等渠道进行第三方登录
- 2、用户可以创建团队进行参赛,但队名不能重复
- 3、用户可以对已参赛的团队进行投票,且每个用户每天投票最多不能超过3次,支持可配置
4、获取已参赛团队的得票排行榜
4.3.4 主要涉及技术功能点
1、使用User扩展类库实现第三方登录操作
- 2、使用缓存存放用户每天投票的次数(为方便起见,使用文件缓存,不落地)
- 3、对接口进行签名验证(为方便起见,固定sign签名)
- 4、数据库的基本操作
- 5、自动化脚本的使用
4.3.4 快速开发流程
(题外音:整个示例的开发,我个人在单元测试驱动开发下,只用了两个多小时,其中还包括对模板场景的业务构思、建表、编写单元测试代码等)。
(1)创建项目和部署环境
把PhalApi最新的框架代码下载后,并将User扩展类库按文档说明配置后,将项目部署到了以下接口域名:
http://api.vote.phalapi.com
测试一下:
http://api.vote.phalapi.com/vote/?sign=phalapi
//返回
{
"ret": 200,
"data": {
"title": "Hello World!",
"content": "PHPer您好,欢迎使用PhalApi!",
"version": "1.1.4",
"time": 1431796924
},
"msg": ""
}
Good! 下面是简明的开发过程。
(2)单元测试驱动开发
在定好接口后:
<?php
class Api_Act extends PhalApi_Api {
public function joinIn() {
}
public function showList() {
}
public function vote() {
}
}
便可使用脚本,快速生成单元测试的骨架代码:
$ cd ./Vote/Tests/Api
$ phalapi_buildtests ../../Api/Act.php Api_Act ../test_env.php > Api_Act_Test.php
(3)快速开发
开发过程此处略,但在单元测试驱动的引导下,很快就产出了以下高质量的代码:
.
├── Api
│ ├── Act.php
│ └── Default.php
├── Common
│ └── SignFilter.php
├── Domain
│ ├── Team.php
│ └── Vote.php
├── Model
│ ├── Team.php
│ ├── UserVoteRecord.php
│ └── Vote.php
└── Tests
├── Api
│ ├── Api_Act_Test.php
│ └── Api_Default_Test.php
├── Domain
├── Model
├── phpunit.xml
└── test_env.php
(4)单元测试全部通过了!
为了方便大家查看,已省略了部分的调试内容,但保留了测试过程中全部执行的SQL语句,如下:
$ phpunit ./Api_Act_Test.php
PHPUnit 4.3.4 by Sebastian Bergmann.
[1 - 0.06911s]DELETE FROM phalapi_team WHERE (team_name = 'test team name');<br>
[2 - 0.06487s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[3 - 0.06553s]SELECT COUNT(id) FROM phalapi_team WHERE (team_name = 'test team name');<br>
[4 - 0.0653s]INSERT INTO phalapi_team (team_name) VALUES ('test team name');<br>
[5 - 0.0699s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[6 - 0.06555s]SELECT COUNT(id) FROM phalapi_team WHERE (team_name = 'test team name');<br>
[9 - 0.06778s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[10 - 0.06603s]SELECT COUNT(id) FROM phalapi_team WHERE (id = 3);<br>
[11 - 0.06825s]SELECT vote_num FROM phalapi_vote WHERE (team_id = 3) LIMIT 1;<br>
[12 - 0.07374s]UPDATE phalapi_vote SET team_id = 3, vote_num = 22 WHERE (team_id = 3);<br>
[13 - 0.07012s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[14 - 0.06682s]SELECT COUNT(id) FROM phalapi_team WHERE (id = 3);<br>
[15 - 0.07433s]SELECT vote_num FROM phalapi_vote WHERE (team_id = 3) LIMIT 1;<br>
[16 - 0.07283s]UPDATE phalapi_vote SET team_id = 3, vote_num = 23 WHERE (team_id = 3);<br>
[17 - 0.07307s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[18 - 0.07501s]SELECT COUNT(id) FROM phalapi_team WHERE (id = 3);<br>
[19 - 0.07135s]SELECT vote_num FROM phalapi_vote WHERE (team_id = 3) LIMIT 1;<br>
[20 - 0.07653s]UPDATE phalapi_vote SET team_id = 3, vote_num = 24 WHERE (team_id = 3);<br>
[21 - 0.07215s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[22 - 0.06722s]SELECT COUNT(id) FROM phalapi_team WHERE (id = 3);<br>
[23 - 0.06506s]SELECT expires_time FROM phalapi_user_session_1 WHERE (user_id = '1') AND (token = '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731');<br>
[24 - 0.06732s]SELECT COUNT(id) FROM phalapi_team WHERE (id = 404);<br>
Time: 1.97 seconds, Memory: 7.00Mb
OK (4 tests, 42 assertions)
(5)运行效果 - Part 1
在我们通过第三方登录后,我们就可以这样进行接口操作了。
首先,让我们添加两个参赛团队:
//奔跑吧兄弟(蓝队)
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.JoinIn&team_name=%E5%A5%94%E8%B7%91%E5%90%A7%E5%85%84%E5%BC%9F%EF%BC%88%E8%93%9D%E9%98%9F%EF%BC%89&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{
"ret": 200,
"data": {
"code": 0,
"team_id": "5"
},
"msg": ""
}
//奔跑吧兄弟(红队)
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.JoinIn&team_name=%E5%A5%94%E8%B7%91%E5%90%A7%E5%85%84%E5%BC%9F%EF%BC%88%E7%BA%A2%E9%98%9F%EF%BC%89&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{
"ret": 200,
"data": {
"code": 0,
"team_id": "6"
},
"msg": ""
}
然后,让我们进行疯狂地投票:
//第一次投票
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.Vote&team_id=5&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{"ret":200,"data":{"code":0,"vote_num":1},"msg":""}
//第二次投票
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.Vote&team_id=5&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{"ret":200,"data":{"code":0,"vote_num":2},"msg":""}
//第三次投票
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.Vote&team_id=5&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{"ret":200,"data":{"code":0,"vote_num":3},"msg":""}
//第四次投票
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.Vote&team_id=5&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回 - 注意此返回!
{"ret":200,"data":{"code":2,"vote_num":0},"msg":""}
最后,看一下排行榜:
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.ShowList&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{
"ret": 200,
"data": {
"code": 0,
"teams": [
{
"id": 5,
"team_name": "奔跑吧兄弟(蓝队)",
"vote_num": 3
},
{
"id": 6,
"team_name": "奔跑吧兄弟(红队)",
"vote_num": 0
}
]
},
"msg": ""
}
至此,我们已经可以把接口交付给客户端同学使用啦!当然,我们还需要稍微整理输出WIKI文档~~~部分接口返回的结果可能与你实际看到的不一样,因为数据会在变化而且有单元测试的测试数据。
(6)运行效果 - Part 2
接口服务,不仅仅需要提供正常的业务功能,还需要考虑到各种客户端使用的情况,包括非法的请求,或者不合的调用,比如防刷票。
这一部分,主要展示接口在各种异常情况下的响应能力。
签名失败
http://api.vote.phalapi.com/vote/?sign=XXX&service=Act.JoinIn&team_name=%E5%A5%94%E8%B7%91%E5%90%A7%E5%85%84%E5%BC%9F%EF%BC%88%E7%BA%A2%E9%98%9F%EF%BC%89&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{
"ret": 400,
"data": [
],
"msg": "非法请求:wrong sign"
}
无登录态
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.JoinIn&team_name=%E5%A5%94%E8%B7%91%E5%90%A7%E5%85%84%E5%BC%9F%EF%BC%88%E7%BA%A2%E9%98%9F%EF%BC%89&token=XXX&user_id=1
//返回
{
"ret": 401,
"data": [
],
"msg": "非法请求:user need to login again"
}
重复参赛
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.JoinIn&team_name=%E5%A5%94%E8%B7%91%E5%90%A7%E5%85%84%E5%BC%9F%EF%BC%88%E7%BA%A2%E9%98%9F%EF%BC%89&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{
"ret": 200,
"data": {
"code": 1,
"team_id": 0
},
"msg": ""
}
当天投票次数已达最大
//第四次投票后
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.Vote&team_id=5&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回 - 注意此返回!
{
"ret": 200,
"data": {
"code": 2,
"vote_num": 0
},
"msg": ""
}
投票的团队不存在
http://api.vote.phalapi.com/vote/?sign=phalapi&service=Act.Vote&team_id=404&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731&user_id=1
//返回
{
"ret": 200,
"data": {
"code": 1,
"vote_num": 0
},
"msg": ""
}
在进行上面的非法请求后,我们可以同时关注后台的日记:
$ tailf ./Runtime/log/201505/20150517.log
2015-05-17 01:35:32|DEBUG|user not login|{"userId":null,"token":null}
2015-05-17 01:36:01|DEBUG|user can not vote today|{"userId":1,"teamId":5}
2015-05-17 01:37:52|DEBUG|user can not vote today|{"userId":1,"teamId":5}
2015-05-17 01:45:25|DEBUG|user need to login again|{"expiresTime":0,"userId":"1","token":"XXX"}
2015-05-17 01:48:13|DEBUG|user can not vote today|{"userId":1,"teamId":5}
(7)需要的数据库表
以下为关键的表,其他表,可以通过脚本自动生成,然后导入。
-- ----------------------------
-- Table structure for `phalapi_team`
-- ----------------------------
DROP TABLE IF EXISTS `phalapi_team`;
CREATE TABLE `phalapi_team` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`team_name` varchar(100) DEFAULT '' COMMENT '队名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of phalapi_team
-- ----------------------------
INSERT INTO `phalapi_team` VALUES ('3', 'egg team');
INSERT INTO `phalapi_team` VALUES ('5', '奔跑吧兄弟(蓝队)');
INSERT INTO `phalapi_team` VALUES ('6', '奔跑吧兄弟(红队)');
INSERT INTO `phalapi_team` VALUES ('17', 'test team name');
INSERT INTO `phalapi_user` VALUES ('1', 'wx_edebc877070133c65161d00799e00544', 'weixinName', '******', '4CHqOhe1Jxi3X9HmRfPOXygDnU267eCA', '1431790647', 'phpunit.png');
INSERT INTO `phalapi_user_login_weixin` VALUES ('1', 'wx_122348561111', 'ASDF', '130000000', '1');
INSERT INTO `phalapi_user_session_1` VALUES ('1', '1', '193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731', '', '1', '1431790647', '1934382647', null);
4.3.4 脚本的使用
(1)创建项目脚本 - phalapi_buildapp
此脚本可用于快速创建项目,其使用如下:
$ ./PhalApi/phalapi-buildapp
Usage: ./PhalApi/phalapi-buildapp <app>
此脚本会根据Demo示例,快速生成一个新的项目。
(2)自动生成单元测试骨架脚本 - phalapi_buildtest
这是一个用来自动生成单元测试骨架的脚本,其使用如下:
$ phalapi-buildtest
Usage:
php /usr/bin/phalapi-buildtest <file_path> <class_name> [bootstrap] [author = dogstar]
Demo:
php ./build_phpunit_test_tpl.php ./Demo.php Demo > Demo_Test.php
然后,我们就可以使用辅助的PhalApi_Helper_TestRunner::go()进行单元测试:
public function testShowList()
{
//Step 1. 构建请求URL
$url = 'service=Act.ShowList&sign=phalapi&user_id=1&token=193CE82D1F4588A9A168BDE6E6B83868B1464F523D16C05206F308E51EB91731';
//Step 2. 执行请求
$rs = PhalApiTestRunner::go($url);
//var_dump($rs);
//Step 3. 验证
$this->assertNotEmpty($rs);
$this->assertArrayHasKey('code', $rs);
$this->assertArrayHasKey('teams', $rs);
$this->assertEquals(0, $rs['code']);
$this->assertNotEmpty($rs['teams']);
foreach ($rs['teams'] as $team) {
$this->assertArrayHasKey('id', $team);
$this->assertArrayHasKey('team_name', $team);
$this->assertArrayHasKey('vote_num', $team);
$this->assertGreaterThanOrEqual(0, $team['vote_num']);
}
}
(3)自动生成分表建表SQL语句 - phalapi_buildsqls
此脚本用于根据dbs.php配置和./Data/*.sql文件生成完整的建表语句,其使用如下:
$ ./PhalApi/phalapi-buildsqls
Usage: ./PhalApi/phalapi-buildsqls <dbs.php> <table> [engine=InnoDB]
假设我们需要对vote进行分表,拆分成3个表,可以这样配置:
//$ vim ./Config/dbs.php
'vote' => array(
'prefix' => 'phalapi_',
'key' => 'id',
'map' => array(
array('start' => 0, 'end' => 2, 'db' => 'db_vote'),
),
),
然后准备基本的建表语句:
//$vim ./Data/vote.sql
`team_id` bigint(20) DEFAULT '0',
`vote_num` int(11) DEFAULT '0',
最后,执行生成脚本:
$ phalapi-buildsqls ./Config/dbs.php vote
/**
* DB: phalapi_vote
*/
CREATE TABLE `phalapi_vote_0` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`team_id` bigint(20) DEFAULT '0',
`vote_num` int(11) DEFAULT '0',
`ext_data` text COMMENT 'json data here',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `phalapi_vote_1` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`team_id` bigint(20) DEFAULT '0',
`vote_num` int(11) DEFAULT '0',
`ext_data` text COMMENT 'json data here',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `phalapi_vote_2` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`team_id` bigint(20) DEFAULT '0',
`vote_num` int(11) DEFAULT '0',
`ext_data` text COMMENT 'json data here',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.3.5 在线接口参数查看
可以通过以下链接,在线实时查看接口参数:
//参赛接口
http://api.vote.phalapi.com/vote/checkApiParams.php?service=Act.JoinIn
//投票接口
http://api.vote.phalapi.com/vote/checkApiParams.php?service=Act.Vote
//排行榜接口
http://api.vote.phalapi.com/vote/checkApiParams.php?service=Act.ShowList
其中,投票接口的参数如下: