上一篇
🚀 当移动端遇上Laravel:用API构建丝滑用户体验
想象一下:用户打开你的APP,点击"发布动态",0.3秒内文字和图片就飞到了服务器,同时收到其他用户的点赞通知,这种流畅体验的背后,正是今天要揭秘的Laravel API开发实战!
composer create-project laravel/laravel api-demo --prefer-dist cd api-demo php artisan serve
✨ 小技巧:用ServBay管理本地环境,PHP8.4+MySQL8.0一键配置,告别版本地狱!
// 安装 composer require laravel/sanctum php artisan migrate // 用户模型添加 use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens; } // 生成Token $token = $user->createToken('mobile-app')->plainTextToken;
✅ 适用场景:移动端/SPA单页面应用,10行代码搞定认证
composer require laravel/passport php artisan migrate php artisan passport:install
🔑 生成客户端:
$client = Passport::client()->create(['name' => 'iOS App']); $token = $user->createToken('iOS')->accessToken;
✅ 适用场景:开放平台/第三方接入,支持PKCE等高级流程
// 基础版 Route::apiResource('posts', PostController::class); // 进阶版(带版本) Route::prefix('v1')->group(function() { Route::apiResource('posts', PostController::class); });
💡 版本控制小贴士:
/api/v1/posts
) Accept: application/vnd.api.v1+json
// app/Http/Resources/PostResource.php public function toArray($request) { return [ 'id' => $this->id, 'content' => $this->content, 'created_at' => (string)$this->created_at, 'links' => [ 'self' => route('posts.show', $this->id) ] ]; } // 控制器中使用 return new PostResource($post);
🎯 统一响应结构:
{ "success": true, "data": {...}, "meta": { "page": 1, "per_page": 15 } }
// 创建自定义异常 class InvalidApiKeyException extends \Exception {} // 在Handler.php中捕获 public function register() { $this->renderable(function(InvalidApiKeyException $e) { return response()->json(['error' => 'Invalid API Key'], 403); }); } // 全局中间件拦截 public function handle($request, Closure $next) { if (!api_key_valid()) { throw new InvalidApiKeyException(); } return $next($request); }
# openapi.yaml paths: /posts: post: requestBody: content: application/json: schema: type: object properties: title: {type: string}
// 运行合同测试 php artisan test --filter=SpectatorTest
// 路由 Route::post('/posts', [PostController::class, 'store']); // 控制器 public function store(StorePostRequest $request) { $post = Auth::user()->posts()->create($request->validated()); return new PostResource($post); }
// 带过滤的查询 Route::get('/posts', [PostController::class, 'index']); public function index(Request $request) { $posts = Post::query() ->when($request->has('category'), function($q) use ($request) { $q->where('category_id', $request->category); }) ->paginate(15); return PostResource::collection($posts); }
缓存策略
Route::get('/popular-posts', function() { return Cache::remember('popular_posts', 3600, function() { return Post::orderBy('views', 'desc')->limit(10)->get(); }); });
速率限制
Route::middleware('throttle:60,1')->group(function() { Route::get('/user/{id}', [UserController::class, 'show']); });
数据库优化
with
预加载关联数据 whereIn
批量查询 💬 互动话题:你在API开发中遇到过哪些坑?是认证问题还是性能瓶颈?欢迎在评论区分享你的故事!
本文由 业务大全 于2025-08-25发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://xdh.7tqx.com/wenda/729883.html
发表评论