THINKPHP5,当初这个框架发布的时候就定义为为API而生,下面我们来看看怎么用TP5来实现Restful Api的查询(get)、增加(post)、修改(put)、删除(delete)等server接口层吧。
REST
(Representational State Transfer表述性状态转移)是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。REST
提出了一些设计概念和准则:
1、网络上的所有事物都被抽象为资源(resource);
2、每个资源对应一个唯一的资源标识(resource identifier);
3、通过通用的连接器接口(generic connector interface)对资源进行操作;
4、对资源的各种操作不会改变资源标识;
5、所有的操作都是无状态的(stateless)。
设置后会自动注册7个路由规则,如下(官方文档):
标识 | 请求类型 | 生成路由规则 | 对应操作方法(默认) |
---|---|---|---|
index | GET | blog |
index |
create | GET | blog/create |
create |
save | POST | blog |
save |
read | GET | blog/:id |
read |
edit | GET | blog/:id/edit |
edit |
update | PUT | blog/:id |
update |
delete | DELETE | blog/:id |
delete |
1.新建api模块,架构如下:
在api/controller下新建一个配置文件 config.php,代码如下:
<?php
return [
'default_return_type' => 'json',
];
2.在api/controller下新建一个控制器test:
<?php
namespace app\api\controller;
use think\Controller;
class Test extends controller
{
public function index()
{
//get
return [
'helloworld',
'helloworld2',
];
}
////修改
public function update($id = 0){
// echo $id;exit;
halt(input('put.'));
//return $id;
}
/**
* post 新增
* @return mixed
*/
public function save(){
$data = input('post.');
return $data;
}
3.定义restful风格的路由规则,application\route.php
<?php
use think\Route;
//get
Route::get('hello', 'api/test/index');
//修改
Route::put('test/:id', 'api/test/update');
//delete
Route::delete('test/:id', 'api/test/delete');
Route::resource('test', 'api/test');
/// x.com/test post => api test save
4.我们用apizza或者POSTMAN工具(自己去百度下载)测试一下:
这样就可以看到结果啦.