thinkphp5½Ó¿ÚÔõÑùд
Ò»¡¢ÇéÐδ
ÎÒÃÇÐèÒªÏÈÔÚÍâµØ½¨ÉèÒ»¸öÄܹ»ÔËÐÐThinkPHP5µÄ¿ª·¢ÇéÐΡ£Ôڴ˲»ÔÙ½²ÊöÏêϸ°ì·¨£¬¿ÉÒԲο¼¹Ù·½Îĵµ»òÆäËû½Ì³Ì¡£½¨ÉèÒ»¸öпØÖÆÆ÷À´´¦Àí½Ó¿ÚÏà¹ØÂß¼£¬ÆäÖÐÌõ¼þÊÇÇéÐÎÒѾ´î½¨ºÃ²¢ÇÒÔÚWebÓ¦ÓóÌÐòÎļþ¼ÐÖС£
¶þ¡¢Â·Óɽç˵
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÔÚ·ÓÉÖнç˵½Ó¿ÚÇëÇó·½·¨ºÍµØµãµÄÓ³Éä¹Øϵ¡£ThinkPHP5ÌṩÁ˼òÆÓÒ×ÓõÄ·Óɽç˵ҪÁì¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
ÀýÈ磬ÎÒÃÇÒª½ç˵һ¸öGETÇëÇóÒªÁìµÄ½Ó¿Ú£¬ÆäµØµãΪyourdomain.com/api/users£¬ÄÇôÎÒÃÇ¿ÉÒÔÔÚ·ÓÉÖнç˵ÈçÏ£º
Route::get('api/users', 'Users/getUserList');
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬api/users Êǽӿڵص㣬UsersÊÇÎÒÃǽ¨ÉèµÄ¿ØÖÆÆ÷£¬getUserListÊǸÿØÖÆÆ÷ÖÐÓÃÓÚ´¦ÀíÇëÇóµÄÒªÁì¡£
Èý¡¢¿ØÖÆÆ÷±àд
½ÓÏÂÀ´£¬ÔÚ¶ÔÓ¦µÄ¿ØÖÆÆ÷ÎļþÖбàд¶ÔÓ¦µÄÒªÁ죬´¦Àí½Ó¿ÚÇëÇó¡£
ÒÔÉÏÊöÀý×ÓΪÀý£¬ÎÒÃÇÔÚ¿ØÖÆÆ÷ÖбàдgetUserListÒªÁ죬ÈçÏ£º
public function getUserList(Request $request) { //»ñÈ¡½Ó¿ÚÇëÇó²ÎÊý $params = $request->param(); //´¦Àí½Ó¿ÚÓªÒµÂß¼ //ÅÌÎÊÓû§Êý¾Ý $users = Db::table('users')->select(); //·µ»Ø½Ó¿ÚÏìÓ¦ return json($users); }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬ÎÒÃÇͨ¹ýRequest¹¤¾ß»ñÈ¡Á˽ӿÚÇëÇó²ÎÊý£¬´ÓÊý¾Ý¿âÖÐÅÌÎÊÁËËùÓеÄÓû§Êý¾Ý£¬²¢Í¨¹ýjsonÒªÁ콫Ч¹ûÒÔjsonÃûÌ÷µ»Ø£¬´Ó¶øÍê³ÉÁËÒ»¸ö¼òÆӵĽӿڵĿª·¢¡£
ËÄ¡¢¹ýʧ´¦Àí
ÁíÍ⣬ÔÚÏÖʵ¿ª·¢Àú³ÌÖУ¬½Ó¿ÚµÄÒì³£´¦ÀíÒ²ÊǺÜÊÇÖ÷ÒªµÄÒ»µã£¬ÐèÒªÔÚ½Ó¿Ú·ºÆðÒ쳣ʱ£¬Ïò¿Í»§¶Ë·µ»ØºÏÊʵĹýʧÐÅÏ¢£¬ÒÔ±ãÓÚ¿Í»§¶Ë¾ÙÐд¦Àí¡£
ÔÚÉÏÊöÀý×ÓÖУ¬Ò»µ©·ºÆðÅÌÎÊÓû§Êý¾ÝµÄÒì³£ÇéÐΣ¬ÐëÕë¶ÔÒì³£¾ÙÐд¦Àí£¬Í¬Ê±·µ»ØÏìÓ¦µÄ¹ýʧÌáÐÑ¡£ÈôÊÇÎÒÃÇʹÓÃÁËtry…catch…½á¹¹À´´¦ÀíÒì³££¬ÄÇôÏìÓ¦µÄ´úÂë»áÊÇÕâ¸öÑù×Ó£º
public function getUserList(Request $request) { try { //»ñÈ¡½Ó¿ÚÇëÇó²ÎÊý $params = $request->param(); //´¦Àí½Ó¿ÚÓªÒµÂß¼ //ÅÌÎÊÓû§Êý¾Ý $users = Db::table('users')->select(); //·µ»Ø½Ó¿ÚÏìÓ¦ return json($users); } catch (\Exception $exception) { //´¦ÀíÒì³££¬·µ»Ø¹ýʧÐÅÏ¢ return json([ 'code' => $exception->getCode(), 'msg' => $exception->getMessage(), ]); } }
µÇ¼ºó¸´ÖÆ
Îå¡¢Çå¾²ÐÔ˼Á¿
×îºó£¬ÎÒÃÇÐèҪ˼Á¿½Ó¿ÚµÄÇå¾²ÐÔÎÊÌâ¡£ºÃ±È£¬ÔõÑù¾ÙÐнӿڻá¼ûȨÏÞ¿ØÖÆ£¬ÔõÑùÌá·À½Ó¿Ú¹¥»÷µÈÎÊÌâ¡£
ThinkPHP5ÌṩÁ˶àÖÖÇå¾²ÐÔ±£»¤²½·¥£¬°üÀ¨µ«²»ÏÞÓÚCSRF·À»¤¡¢SQL×¢Èë·À»¤ºÍXSS·À»¤¡£Äã¿ÉÒÔƾ֤ÏêϸÇéÐÎÑ¡Ôñ¶ÔÓ¦µÄ·À»¤²½·¥¾ÙÐÐÉèÖá£
ÁíÍ⣬½Ó¿Ú»á¼ûȨÏÞ¿ØÖÆÒ²ÊǺÜÊÇÐëÒªµÄ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔÔÚ·Óɽç˵ÖмÓÈëÈçÏ´úÂ룺
Route::get('api/users', 'Users/getUserList')->middleware('apiAuth');
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬middlewareÊÇThinkPHP5ÖеÄÒ»ÆäÖÐÐļþ´¦Àíº¯Êý£¬¿ÉÓÃÓÚʵÏֽӿڵĻá¼ûȨÏÞ¿ØÖƵȹ¦Ð§¡£Äã¿ÉÒÔƾ֤ÏÖʵÐèÇó±àд¶ÔÓ¦µÄÖÐÐļþÂß¼¡£
ÒÔÉϾÍÊÇthinkphp5½Ó¿ÚÔõÑùдµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡