Use ThinkPHP Develope API

Create database data

Import this sql file into your database, you can commit execute sql or import by tools:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='新闻表';

-- ----------------------------
-- Records of news
-- ----------------------------
INSERT INTO `news` VALUES ('1', '新闻1', '新闻1内容');
INSERT INTO `news` VALUES ('2', '新闻2', '新闻2内容');
INSERT INTO `news` VALUES ('3', '新闻3', '新闻3内容');
INSERT INTO `news` VALUES ('4', '房价又涨了', '据新华社消息:上海均价环比上涨5%');

Write API

Wechat Official Account documents:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840

image

New files: application/api/controller/News.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
namespace app\api\controller;

use think\Controller;

class News extends Controller
{
public function read()
{
$id = input('id');
$model = model('News');
$data = $model->getNews($id);
if ($data) {
$code = 200;
} else {
$code = 404;
}
$data = [
'code' => $code,
'data' => $data
];
return json($data);
}
}

New files: application/api/model/News.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace app\api\model;

use think\Model;
use think\Db;

class News extends Model
{
public function getNews($id = 1)
{
$res = Db::name('news')->where('id', $id)->select();
return $res;
}

public function getNewsList()
{
$res = Db::name('news')->select();
return $res;
}
}

Visit API:

image

Shorten API address

According to the ThinkPHP router rules, we can edit it in application/route.php

1
2
3
use think\Route;

Route::rule('news/:id','api/news/read');

Visit new route:

image

Exchange blogroll: http://laker.me/blog
Github:https://github.com/younglaker


Use ThinkPHP Develope API

本文原创自http://laker.me/blog,转载请注明出处,欢迎交换友链

如果本文对您有帮助,微信扫一扫,请我吃个鸡腿吧