RESTful

使用 IMI 提供的路由请求方法判断,可以实现 RESTful 风格的 api 开发。

RESTful 风格控制器示例 (query/find/create/update/delete):

  1. <?php
  2. namespace ImiDemo\HttpDemo\MainServer\Controller;
  3. use Imi\Controller\HttpController;
  4. use Imi\Server\View\Annotation\View;
  5. use Imi\Server\Route\Annotation\Route;
  6. use Imi\Server\Route\Annotation\Action;
  7. use Imi\Server\Route\Annotation\Controller;
  8. /**
  9. * @Controller(prefix="/Rest/")
  10. * @View(renderType="json")
  11. */
  12. class Rest extends HttpController
  13. {
  14. /**
  15. * query
  16. *
  17. * @Action
  18. * @Route(url="", method={"GET"})
  19. * @return void
  20. */
  21. public function query()
  22. {
  23. return [1, 2, 3];
  24. }
  25. /**
  26. * find
  27. *
  28. * @Action
  29. * @Route(url="{id}", method={"GET"})
  30. *
  31. * @param int $id
  32. * @return void
  33. */
  34. public function find($id)
  35. {
  36. return [
  37. 'id' => $id,
  38. ];
  39. }
  40. /**
  41. * create
  42. *
  43. * @Action
  44. * @Route(url="", method={"POST"})
  45. * @return void
  46. */
  47. public function create()
  48. {
  49. return [
  50. 'operation' => 'create',
  51. 'postData' => $this->request->getParsedBody(),
  52. 'success' => true,
  53. ];
  54. }
  55. /**
  56. * update
  57. *
  58. * @Action
  59. * @Route(url="{id}", method={"PUT"})
  60. *
  61. * @param int $id
  62. * @return void
  63. */
  64. public function update($id)
  65. {
  66. return [
  67. 'id' => $id,
  68. 'operation' => 'update',
  69. 'success' => true,
  70. ];
  71. }
  72. /**
  73. * delete
  74. *
  75. * @Action
  76. * @Route(url="{id}", method={"DELETE"})
  77. *
  78. * @param int $id
  79. * @return void
  80. */
  81. public function delete($id)
  82. {
  83. return [
  84. 'id' => $id,
  85. 'operation' => 'delete',
  86. 'success' => true,
  87. ];
  88. }
  89. }