thinkphp6ÔõÑùÉèÖÃapi
Ëæ×Å»¥ÁªÍøµÄѸËÙÉú³¤£¬apiÒѳÉΪÏÖ½ñ»¥ÁªÍøÓ¦ÓÃÖеÄÖ÷Òª×é³É²¿·Ö¡£apiÔÊÐíÓ¦ÓóÌÐòÖ®¼äÏ໥ͨѶ£¬´Ó¶øʹµÃ¶à¸öÓ¦ÓóÌÐòÄܹ»ÐͬÊÂÇ飬Ìá¸ßÁË»¥ÁªÍøÓ¦ÓõĿÉÀ©Õ¹ÐԺͿÉά»¤ÐÔ¡£¶øÔÚʹÓÃphp¿ò¼ÜÀ´¹¹½¨Ó¦ÓóÌÐòʱ£¬ÔõÑùÉèÖÃapi³ÉΪÁË¿ª·¢ÕßÃÇÌåÌùµÄÒ»¸öÎÊÌâ¡£
ÔÚÕâƪÎÄÕÂÖУ¬ÎÒÃǽ«ÏÈÈÝÔõÑùʹÓÃThinkPHP6¿ò¼ÜÀ´ÉèÖÃAPI¡£ThinkPHP6ÊÇÒ»¸ö¸ßЧ¡¢¾«Á·¡¢ÎÞаµÄPHP¿ª·¢¿ò¼Ü£¬ËüÌṩÁËÇ¿Ê¢µÄ¹¤¾ßºÍ¹¦Ð§£¬Ö§³Ö¿ìËÙ½¨ÉèWEBÓ¦ÓóÌÐò¡¢RESTFUL APIÒÔ¼°Î¢Ð§À͵ȡ£ÏÂÃæÎÒÃǽ«ÏêϸÏÈÈÝÔõÑùʹÓÃThinkPHP6À´¹¹½¨RESTful API¡£
Ò»¡¢APIÉè¼ÆÔÔò
ÔÚ¹¹½¨APIʱ£¬ÐèÒª×ñÕÕһЩÉè¼ÆÔÔò¡£ÒÔÏÂÊÇһЩ³£ÓõÄAPIÉè¼ÆÔÔò£º
1.ʹÓÃRESTful¼Ü¹¹
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
REST£¨Representational State Transfer£©ÊÇÒ»ÖÖÓÃÓÚ¹¹½¨ÂþÑÜʽϵͳµÄÈí¼þ¼Ü¹¹ÆøÑæÆøÑ档ʹÓÃRESTful¼Ü¹¹¿ÉÒÔʹµÃAPI¾ßÓпÉÀ©Õ¹ÐÔ¡¢ÎȹÌÐÔºÍÒ×ÓÚά»¤µÄÓÅÊÆ¡£
2.ʹÓÃHTTPÐÒé
APIͨ³£Ê¹ÓÃHTTPÐÒéÀ´¾ÙÐÐͨѶ¡£HTTPÐÒéÊÇÒ»¸öÇáÁ¿¼¶µÄÇëÇó/ÏìÓ¦ÐÒ飬Ëü¾ßÓÐÆÕ±éµÄÓ¦Óó¡¾°ºÍÒ×ÓÚʹÓõÄÌص㡣
3.ʹÓñê×¼ÃûÌÃ
ÔÚAPIͨѶÀú³ÌÖУ¬ÐèҪʹÓñê×¼µÄÊý¾Ý½»Á÷ÃûÌã¬ÈçJSON»òXML¡£ÕâЩÊý¾Ý½»Á÷ÃûÌþßÓÐͨÓÃÐÔºÍÒ×ÓÚÆÊÎöµÄÌص㣬ʹµÃÊý¾Ý½»Á÷Ô½·¢±ã½ÝºÍ¸ßЧ¡£
4.Ìṩ°æ±¾¿ØÖÆ
APIÉæ¼°µ½Êý¾ÝºÍÓªÒµÂß¼µÄ½»»¥£¬ÎªÁË°ü¹Ü¼æÈÝÐÔ£¬ÐèÒªÌṩ°æ±¾¿ØÖÆÄÜÁ¦¡£
¶þ¡¢ThinkPHP6ÖÐÉèÖÃRESTful API
ÔÚThinkPHP6ÖУ¬¿ÉÒÔͨ¹ýÒÔÏ°취À´¹¹½¨RESTful API£º
1.½¨Éè¿ØÖÆÆ÷
Ê×ÏÈ£¬ÐèÒª½¨ÉèÒ»¸ö¿ØÖÆÆ÷ÓÃÓÚÏìÓ¦RESTful APIÇëÇó¡£
namespace appcontroller;
use thinkRequest;
class ApiController
{
// »ñÈ¡Óû§ÐÅÏ¢ public function getUserInfo(Request $request, $id) { // ƾ֤Óû§id»ñÈ¡Óû§ÐÅÏ¢ $userInfo = [ 'id' => $id, 'name' => 'ÕÅÈý', 'phone' => '123456789', 'address' => '±±¾©ÊÐÏòÑôÇø' ]; // ·µ»ØJSONÃûÌõÄÏìÓ¦ return json($userInfo); }
µÇ¼ºó¸´ÖÆ
}
ÔÚÉÏÃæµÄ´úÂëÖУ¬½¨ÉèÁËÒ»¸öÃûΪApiControllerµÄ¿ØÖÆÆ÷£¬ÆäÖаüÀ¨Ò»¸ögetUserInfo()ÒªÁ죬¸ÃÒªÁìÓÃÓÚ»ñÈ¡Óû§ÐÅÏ¢²¢·µ»ØJSONÃûÌõÄÏìÓ¦¡£
2.½¨Éè·ÓÉ
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸ö·ÓÉÓÃÓÚ½«APIÇëÇó·Óɵ½¿ØÖÆÆ÷ÖС£ÔÚThinkPHP6ÖУ¬Â·ÓÉ¿ÉÒÔͨ¹ý·ÓÉÎļþÀ´½ç˵¡£ÔÚĬÈÏÇéÐÎÏ£¬Â·ÓÉÎļþλÓÚapp/routesĿ¼Ï¡£ÏÂÃæÊÇÒ»¸öÓÃÓÚÉùÃ÷GETÇëÇóµÄ·ÓÉʾÀý£º
use thinkacadeRoute;
Route::get(‘api/user/:id’, ‘ApiController@getUserInfo’);
ÔÚÕâ¸ö·ÓÉÖУ¬Ö¸¶¨ÁËGETÒªÁìµÄÇëÇóURIΪ/api/user/:id£¬ÆäÖÐ:idÊǶ¯Ì¬µÄ²ÎÊý£¬ÌåÏÖÒª»ñÈ¡Óû§µÄid¡£ÔÚURIºóÃæ½ôËæ×ŵÄÊÇ¿ØÖÆÆ÷µÄÃû³ÆÒÔ¼°ÒªÅ²ÓõÄÒªÁìÃû³Æ£¬ÓÉ¡°@¡±·ûºÅÅþÁ¬¡£
3.²âÊÔRESTful API
µ±½¨ÉèºÃ¿ØÖÆÆ÷ºÍ·Óɺó£¬ÎÒÃǾͿÉÒÔ²âÊÔRESTful APIÊÇ·ñÄܹ»Õý³£ÊÂÇéÁË¡£ÔÚä¯ÀÀÆ÷ÖÐÊäÈëAPIµÄÇëÇóURI£¨Èçhttp://localhost/api/user/1£©£¬ÏµÍ³¾Í»áƾ֤·ÓÉÉèÖã¬Å²ÓÃApiControllerÖеÄgetUserInfo()ÒªÁìÀ´»ñÈ¡Óû§ÐÅÏ¢¡£
×ܽá
±¾ÎÄÏÈÈÝÁËÔõÑùʹÓÃThinkPHP6¿ò¼ÜÀ´¹¹½¨RESTful API¡£ÔÚ¹¹½¨APIʱ£¬ÐèÒª×ñÕÕһЩÉè¼ÆÔÔò£¬ÈçʹÓÃRESTful¼Ü¹¹¡¢Ê¹ÓÃHTTPÐÒ顢ʹÓñê×¼ÃûÌÃÒÔ¼°Ìṩ°æ±¾¿ØÖÆÄÜÁ¦¡£ÔÚThinkPHP6ÖУ¬¿ÉÒÔͨ¹ý½¨Éè¿ØÖÆÆ÷ºÍ·ÓÉÀ´ÊµÏÖAPIµÄ¹¹½¨¡£
ÒÔÉϾÍÊÇthinkphp6ÔõÑùÉèÖÃapiµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡