laravelÔõÑùдapi
laravel×÷ΪһÃÅÊ¢ÐеÄphp¿ò¼Ü£¬ÒѾ³ÉΪÁË¿ª·¢Ö°Ô±Ð´apiµÄÊ×Ñ¡¡£Í¨¹ýlaravel£¬Äã¿ÉÒÔ¿ìËÙ±àд¸ßÖÊÁ¿µÄapi£¬ÆäÔ½À´Ô½Êܵ½ÆóÒµ¼¶ºÍСÎÒ˽ÈË¿ª·¢ÕߵĽӴý¡£
ÔÚÕâƪÎÄÕÂÖУ¬ÎÒÃǽ«Ì½ÌÖÔõÑùʹÓÃLaravel±àдAPI¡£ÎÒÃǽ«´ÓÒÔϼ¸¸ö·½ÃæÈëÊÖ£º¹¹½¨API¡¢API·ÓÉ¡¢¿ØÖÆÆ÷ºÍAPI²âÊÔ¡£
¹¹½¨API
ÔÚ¹¹½¨APIʱ£¬ÐèҪʹÓÃLaravelÌṩµÄÄÚÖÃÖÐÑë¼þºÍ·ÓÉÆ÷¡£´ÓLaravel 5.5×îÏÈ£¬¿ò¼ÜÄÚÖÃÁËAPI×ÊÔ´¿ØÖÆÆ÷£¨API Resource Controller£©¹¦Ð§¡£Õâ¸öÌØÕ÷ʹµÃ¿ª·¢Õß¿ÉÒÔ¸ü¿ìµÄ½¨Éè±ê×¼µÄREST API£¬²¢ÇÒ×ÊÖú¿ª·¢Õßά»¤´úÂëÒ»ÖÂÐÔ¡£
ÔõÑùʹÓÃ×ÊÔ´¿ØÖÆÆ÷£¿Ê×ÏÈ£¬ÔÚÏÂÁîÐÐÖÐÖ´ÐÐÒÔÏÂÏÂÁн¨Ò»¸ö¿ØÖÆÆ÷£º
php artisan make:controller Api/PostController --api
µÇ¼ºó¸´ÖÆ
Õâ»á½¨ÉèÒ»¸öÃûΪPostControllerµÄAPI¿ØÖÆÆ÷£¬Ëü½«×Ô¶¯¼ÌÐøLaravelµÄÄÚÖõÄResourceController£¬²¢ÇÒ°üÀ¨ËùÓеÄÔ¤½ç˵µÄÒªÁì¡£ÕâЩҪÁì°üÀ¨£ºindex¡¢show¡¢store¡¢updateºÍdestroy¡£
API·ÓÉ
ÔÚLaravelÖУ¬Â·ÓÉÓë¿ØÖÆÆ÷ϸÃÜñîºÏ£¬ÓÉÓÚÎÒÃÇÐèÒªÔÚ·ÓÉÖнç˵´¦ÀíAPIÇëÇóµÄ¶¥¼¶¿ØÖÆÆ÷¡£
Route::prefix('api')->group(function () { Route::resource('posts', 'Api\PostController'); });
µÇ¼ºó¸´ÖÆ
Õâ¸ö·Óɽç˵ÁËÒ»¸ö’/api/posts’µÄURL£¬ÓÃÀ´²Ù×÷PostÄ£× CRUD ¹¦Ð§¡£
¿ØÖÆÆ÷
ÔÚ×ÊÔ´¿ØÖÆÆ÷ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÔ¤½ç˵µÄº¯ÊýÀ´´¦Àí³£¼ûµÄʹÃü¡£ÀýÈ磬ÏÂÃæµÄ´úÂë×îÏȽ¨Éè²¢¸½¼ÓpostÎÄÕµÄÎļþÉÏ´«£¬½«Îļþ´Ó´æ´¢¿âÖÐÒƶ¯µ½¹«¹²Ä¿Â¼ÖУº
public function store(Request $request) { $path = $request->file('photo')->store('public/photos'); $post = new Post; $post->title = $request->input('title'); $post->description = $request->input('description'); $post->slug = str_slug($request->input('title')); $post->photo = $path; $post->save(); return new Resource($post); }
µÇ¼ºó¸´ÖÆ
API²âÊÔ
²âÊÔAPIÊÇÈ·±£Æ书ЧÕý³£ÊÂÇéµÄÒªº¦£¬ÇëÈ·±£ÔÚ±àдAPIʱ±àд²âÊÔÓÃÀý¡£LaravelÒ²ÄÚÖÃÁË¿ò¼Ü²âÊÔ¹¤¾ßÀ´×ÊÖúÄúÇáËɵرàд²âÊÔÓÃÀý¡£
ÔÚΪAPI±àд²âÊÔʱ£¬Äú¿ÉÒÔʹÓ÷¢ËÍHTTPÇëÇó²¢¼ì²éÏìÓ¦µÄÒªÁìÀ´²âÊÔ¿ØÖÆÆ÷¡£ÀýÈ磬ÏÂÃæµÄ´úÂë²âÊÔ¿ØÖÆÆ÷ÊÇ·ñ¿ÉÒÔ׼ȷµØ»ñÈ¡Ìû×ÓµÄÁÐ±í£º
public function testPostIndex() { $response = $this->json('GET', '/api/posts'); $response->assertStatus(200); $response->assertJsonStructure([ 'data' => [ '*' => [ 'id', 'title', 'description', 'slug', 'photo', 'created_at', 'updated_at' ] ] ]); }
µÇ¼ºó¸´ÖÆ
½áÂÛ
ÔÚLaravelÖУ¬±àдAPIºÜÊÇÈÝÒס£Ê¹ÓÃÔ¤½ç˵µÄAPI¿ØÖÆÆ÷ºÍÄÚÖõÄ·ÓÉÆ÷£¬Äú¿ÉÒÔ¿ìËÙ½¨Éè±ê×¼µÄREST API¡£Ê¹ÓÃLaravelµÄ²âÊÔ¹¤¾ß±àд²âÊÔÓÃÀý£¬¼ì²éAPI¹¦Ð§ÊÇ·ñÕý³£ÊÂÇé¡£ÓÅÒìµÄÎĵµºÍÉçÇøÖ§³Ö£¬ÊÇÈÃLaravel³ÉΪ¿ª·¢Ö°Ô±×îÊܽӴýµÄ¿ò¼ÜÖ®Ò»µÄÒªº¦ÒòËØ¡£
ÒÔÉϾÍÊÇlaravelÔõÑùдapiµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡