RESTful

通过 HTTP服务 - Controller 中路由功能, 可以很轻松的实现一个 RESTful 风格的 HTTP服务.

代码参考 app/Controllers/RestController:

  1. <?php
  2. namespace App\Controllers;
  3. use Swoft\Http\Server\Bean\Annotation\Controller;
  4. use Swoft\Http\Server\Bean\Annotation\RequestMapping;
  5. use Swoft\Http\Server\Bean\Annotation\RequestMethod;
  6. use Swoft\Http\Message\Server\Request;
  7. /**
  8. * RESTful和参数验证测试demo
  9. *
  10. * @Controller(prefix="/user")
  11. */
  12. class RestController
  13. {
  14. /**
  15. * 查询列表接口
  16. * 地址:/user/
  17. *
  18. * @RequestMapping(route="/user", method={RequestMethod::GET})
  19. */
  20. public function list()
  21. {
  22. return ['list'];
  23. }
  24. /**
  25. * 创建一个用户
  26. * 地址:/user
  27. *
  28. * @RequestMapping(route="/user", method={RequestMethod::POST,RequestMethod::PUT})
  29. *
  30. * @param Request $request
  31. *
  32. * @return array
  33. */
  34. public function create(Request $request)
  35. {
  36. $name = $request->input('name');
  37. $bodyParams = $request->getBodyParams();
  38. $bodyParams = empty($bodyParams) ? ["create", $name] : $bodyParams;
  39. return $bodyParams;
  40. }
  41. /**
  42. * 查询一个用户信息
  43. * 地址:/user/6
  44. *
  45. * @RequestMapping(route="{uid}", method={RequestMethod::GET})
  46. *
  47. * @param int $uid
  48. *
  49. * @return array
  50. */
  51. public function getUser(int $uid)
  52. {
  53. return ['getUser', $uid];
  54. }
  55. /**
  56. * 查询用户的书籍信息
  57. * 地址:/user/6/book/8
  58. *
  59. * @RequestMapping(route="{userId}/book/{bookId}", method={RequestMethod::GET})
  60. *
  61. * @param int $userId
  62. * @param string $bookId
  63. *
  64. * @return array
  65. */
  66. public function getBookFromUser(int $userId, string $bookId)
  67. {
  68. return ['bookFromUser', $userId, $bookId];
  69. }
  70. /**
  71. * 删除一个用户信息
  72. * 地址:/user/6
  73. *
  74. * @RequestMapping(route="{uid}", method={RequestMethod::DELETE})
  75. *
  76. * @param int $uid
  77. *
  78. * @return array
  79. */
  80. public function deleteUser(int $uid)
  81. {
  82. return ['delete', $uid];
  83. }
  84. /**
  85. * 更新一个用户信息
  86. * 地址:/user/6
  87. *
  88. * @RequestMapping(route="{uid}", method={RequestMethod::PUT, RequestMethod::PATCH})
  89. *
  90. * @param int $uid
  91. * @param Request $request
  92. * @return array
  93. */
  94. public function updateUser(Request $request, int $uid)
  95. {
  96. $body = $request->getBodyParams();
  97. $body['update'] = 'update';
  98. $body['uid'] = $uid;
  99. return $body;
  100. }
  101. }