ThinkPHP6 API接口开发项目实战_第1页
ThinkPHP6 API接口开发项目实战_第2页
ThinkPHP6 API接口开发项目实战_第3页
ThinkPHP6 API接口开发项目实战_第4页
ThinkPHP6 API接口开发项目实战_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ThinkPHP6API接口开发1.环境准备与项目创建bashcomposercreate-projecttopthink/thinktp6-apicdtp6-api安装完成后,配置.env文件中的数据库连接信息。2.目录结构与命名约定推荐使用以下目录结构组织API相关代码:textapp/├──api///API模块目录│├──controller///控制器│├──model///模型│├──validate///验证器│└──route///独立路由文件(可选)├──BaseController.php//基础控制器└──...在config/app.php中开启多应用模式(默认已开启):php'auto_multi_app'=>true,3.路由配置在route/app.php(或route/api.php)中定义API路由:phpusethink\facade\Route;//分组+版本控制Route::group('v1',function(){//资源路由(自动生成7个常用接口)Route::resource('users','User');//自定义路由Route::post('login','Auth/login');Route::get('profile','User/profile')->middleware('auth');})->prefix('api/v1.');//指向app\api\v1\controller如果希望路由文件分离,在config/route.php中设置:php'route_file'=>['api'=>'api/route/api.php',],4.控制器编写创建app\api\v1\controller\User.php:php<?phpnamespaceapp\api\v1\controller;useapp\BaseController;usethink\exception\ValidateException;useapp\api\v1\model\UserasUserModel;classUserextendsBaseController{protected$middleware=['auth'];//控制器中间件//列表GET/v1/userspublicfunctionindex(){$list=UserModel::paginate(15);returnjson(['code'=>200,'msg'=>'success','data'=>$list]);}//单个详情GET/v1/users/:idpublicfunctionread($id){$user=UserModel::find($id);if(!$user){returnjson(['code'=>404,'msg'=>'用户不存在'],404);}returnjson($user);}//创建POST/v1/userspublicfunctionsave(){$data=$this->request->post();//使用验证器try{validate(\app\api\v1\validate\User::class)->check($data);}catch(ValidateException$e){returnjson(['code'=>422,'msg'=>$e->getError()],422);}$user=UserModel::create($data);returnjson(['code'=>201,'data'=>$user],201);}//更新PUT/v1/users/:idpublicfunctionupdate($id){$data=$this->request->put();$user=UserModel::find($id);if(!$user){returnjson(['code'=>404,'msg'=>'用户不存在'],404);}$user->save($data);returnjson(['code'=>200,'msg'=>'更新成功']);}//删除DELETE/v1/users/:idpublicfunctiondelete($id){$user=UserModel::find($id);if($user){$user->delete();}returnjson(['code'=>204,'msg'=>'删除成功'],204);}}5.模型层模型继承\think\Model,建议使用软删除、自动时间戳等特性。php<?phpnamespaceapp\api\v1\model;usethink\Model;classUserextendsModel{protected$table='users';protected$autoWriteTimestamp=true;protected$hidden=['password'];//隐藏敏感字段//修改器:密码加密publicfunctionsetPasswordAttr($value){returnpassword_hash($value,PASSWORD_DEFAULT);}}6.验证器验证器放在app\api\v1\validate\User.php:php<?phpnamespaceapp\api\v1\validate;usethink\Validate;classUserextendsValidate{protected$rule=['username'=>'require|max:20|unique:users','email'=>'require|email|unique:users','password'=>'require|length:6,20',];protected$message=['username.require'=>'用户名必须','email.require'=>'邮箱必须',];//场景控制(可选)protected$scene=['login'=>['username','password'],];}7.请求与响应规范统一响应格式创建一个ApiResponsetrait或基类方法:phptraitApiResponse{protectedfunctionsuccess($data=[],$msg='success',$code=200){returnjson(['code'=>$code,'msg'=>$msg,'data'=>$data,'time'=>time()]);}protectedfunctionerror($msg='error',$code=400,$data=[]){returnjson(['code'=>$code,'msg'=>$msg,'data'=>$data,],$code);}}在控制器中使用useApiResponse;即可调用。全局异常处理修改app\ExceptionHandle.php的render方法,使API模式返回JSON:phppublicfunctionrender($request,Throwable$e){if($request->isAjax()||$request->isJson()){returnjson(['code'=>$e->getCode()?:500,'msg'=>$e->getMessage()],500);}returnparent::render($request,$e);}8.中间件JWT身份验证中间件安装firebase/php-jwt:bashcomposerrequirefirebase/php-jwt创建中间件app\http\middleware\Auth.php:php<?phpnamespaceapp\http\middleware;useFirebase\JWT\JWT;useFirebase\JWT\Key;classAuth{publicfunctionhandle($request,\Closure$next){$token=$request->header('Authorization');$token=str_replace('Bearer','',$token);try{$decoded=JWT::decode($token,newKey(config('app.jwt_key'),'HS256'));$request->user=$decoded->data;//注入用户信息}catch(\Exception$e){returnjson(['code'=>401,'msg'=>'未授权或令牌失效'],401);}return$next($request);}}注册中间件config/middleware.php:phpreturn['alias'=>['auth'=>\app\http\middleware\Auth::class,],];CORS跨域中间件php//中间件app\http\middleware\Cors.phppublicfunctionhandle($request,\Closure$next){header('Access-Control-Allow-Origin:*');header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS');header('Access-Control-Allow-Headers:Content-Type,Authorization');if($request->method()==='OPTIONS'){exit;}return$next($request);}9.数据转换(资源类)ThinkPHP6没有内置的资源类,但可以手动实现或使用第三方扩展。推荐使用league/fractal或自己编写简单的转换层。示例:创建app\api\v1\resource\UserResource.phpphpclassUserResource{publicstaticfunctiontoArray($user){return['id'=>$user->id,'name'=>$user->username,'email'=>$user->email,'avatar'=>$user->avatar?url($user->avatar):null,'created_at'=>$user->create_time,];}}在控制器中使用:phpreturn$this->success(UserResource::toArray($user));10.接口文档生成推荐使用注解方式生成OpenAPI(Swagger)文档。安装zircote/swagger-php:bashcomposerrequirezircote/swagger-php在控制器方法上写注解:php/***@OA\Get(*path="/v1/users",*summary="获取用户列表",*@OA\Response(response=200,description="成功")*)*/publicfunctionindex(){...}然后执行vendor/bin/openapi--outputpublic/swagger.jsonapp/api生成文档。11.性能优化建议开启路由缓存:phpthinkoptimize:route配置数据库连接池(如使用Swoole)使用Redis缓存频繁查询的数据对返回数据使用json_encode选项:json($data,200,['Content-Type'=>'application/json'],JSON_UNESCAPED_UNICODE)12.示例:完整用户登录流程php//AuthController.phppublicfunctionlogin(Request$request){$data=$reques

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论