ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 知识参考资料 >关于restful介绍,百度 官方文档[ThinkPHP5快速入门 之 API开发](https://www.kancloud.cn/thinkphp/thinkphp5_quickstart/160681) # 开发流程及步骤 thinkphp开发restful,主需要两步 * 第一 按规范要求 控制器中写好对应7个方法 【返回必须为json】 * 第二 路由中,对应控制器开发资源路由,实例如下 >[warning] 其它 控制需要注意问题,处理空操作,异常,防止暴露系统信息 # 基本配置 * 项目目录结构 ~~~ www WEB部署目录(或者子目录) ├─apps 应用目录 │ ├─common 公共模块目录(可以更改) │ ├─api 模块目录 │ │ ├─common.php 模块函数文件 │ │ ├─controller 控制器目录 │ │ ├─model 模型目录 │ │ ├─view 视图目录 │ │ ├─config 配置目录 │ │ └─ ... 更多类库目录 │ │ │ ├─command.php 命令行定义文件 │ ├─common.php 公共函数文件 │ └─tags.php 应用行为扩展定义文件 │ ├─config 应用配置目录 │ ├─api 模块配置目录 │ │ ├─database.php 数据库配置 │ ......... ├─route 路由定义目录 │ ├─route.php 路由定义 │ └─... 更多 ~~~ ## 引导入口文件 * 引导文件 index.php ~~~ <?php use think; // 定义应用目录 define('APP_PATH', __DIR__ . '/apps/'); // 绑定到index模块 define('BIND_MODULE', 'api/index'); // 加载框架引导文件 require __DIR__ . '/thinkphp/base.php'; // 执行应用并响应 Container::get('app', [APP_PATH])->run()->send(); ~~~ * route\route.php文档配置 ~~~ <?php return [ '__rest__' =>[ 'api' => 'api/restful', ] ]; ~~~ ## 应用开发 controller/Restful.php 接口控制器 >[info]建议文件使用系统自带命令行进行自动生成 `php think make:controller api\Restful` * api/controller/Restful.php ~~~ <?php namespace app\api\controller; use think\Controller; use think\Request; /* * 最基本是简化操作,直接与数据库中表进行一一对应 */ class Restful extends Controller { /** * 显示资源列表 * * @return \think\Response */ public function index() { // abort(404,'index error'); return json(['name'=>'index','data'=>input()]); } /** * 显示创建资源表单页. * * @return \think\Response */ public function create() { // return json(['name'=>'create','data'=>input()]); } /** * 保存新建的资源 * * @param \think\Request $request * @return \think\Response */ public function save(Request $request) { // return json(['name'=>'index','data'=>$request->post()]); } /** * 显示指定的资源 * * @param int $id * @return \think\Response */ public function read($id) { // dump(config()); // // abort(404,'index error'); return json(['name'=>'read','id'=>$id,'data'=>input()]); } /** * 显示编辑资源表单页. * * @param int $id * @return \think\Response */ public function edit($id) { // return json(['name'=>'edit','id'=>$id,'data'=>input()]); } /** * 保存更新的资源 * * @param \think\Request $request * @param int $id * @return \think\Response */ public function update(Request $request, $id) { // return json(['name'=>'update','id'=>$id,'data'=>input()]); } /** * 删除指定资源 * * @param int $id * @return \think\Response */ public function delete($id) { return json(['name'=>'delete','id'=>$id,'data'=>input()]); // } } ~~~ ## 测试 浏览器 http://127.0.0.1/xxxx/index.php/api 测试工具,建议如官方文档[ThinkPHP5快速入门 之 API开发](https://www.kancloud.cn/thinkphp/thinkphp5_quickstart/160681) * 使用专用postman, * 浏览 F12,控制台使用jquery [*默认浏览器,主要测试get方式*] * 借助于php Guzzle库[使用Guzzle进行API测试](http://www.php1024.com/posts/15.htm)