Restful

Biny也同时支持restful协议的请求,可以在Action类中将$restApi置为true,则该Action会以restful的协议来解析路由

  1. namespace app\controller;
  2. /**
  3. * restful演示
  4. * @property \app\dao\userDAO $userDAO
  5. */
  6. class restAction extends baseAction
  7. {
  8. // 该action以restful协议解析路由
  9. protected $restApi = true;
  10.  
  11. // [GET] http://www.billge.cc/rest/?id=xxx
  12. public function GET_index($id)
  13. {
  14. $user = $this->userDAO->filter(['id'=>$id])->find();
  15. return $user ? $this->correct($user) : $this->error('user not found');
  16. }
  17.  
  18. // [POST] http://www.billge.cc/rest/test
  19. public function POST_test()
  20. {
  21. $user = $this->param('user');
  22. $user_id = $this->userDAO->add($user);
  23. return $user_id ? $this->correct($user) : $this->error('data error');
  24. }
  25.  
  26. // [PUT] http://www.billge.cc/rest/?id=xxx
  27. public function PUT_index($id)
  28. {
  29. $user = $this->param('user');
  30. $ret = $this->userDAO->filter(['id'=>$id])->update($user);
  31. return $ret ? $this->correct() : $this->error('data error');
  32. }
  33.  
  34. // [PATCH] http://www.billge.cc/rest/test?id=xxx
  35. public function PATCH_test($id)
  36. {
  37. $sets = $this->param('sets');
  38. $ret = $this->userDAO->filter(['id'=>$id])->update($sets);
  39. return $ret ? $this->correct() : $this->error('data error');
  40. }
  41.  
  42. // [DELETE] http://www.billge.cc/rest/test?id=xxx
  43. public function DELETE_test($id)
  44. {
  45. $ret = $this->userDAO->filter(['id'=>$id])->delete();
  46. return $ret ? $this->correct() : $this->error('data error');
  47. }
  48. }

同样,restful协议也可以通过自定义路由的模式来配置,例如

  1. /config/config.php
  2. 'routeRule' => array(
  3. // rest/(\d+) 的restful路由会自动转发到restAction中的 {method}_test方法
  4. 'rest/<id:\d+>' => 'rest/test',
  5. // 匹配的参数可在转发路由中动态使用
  6. 'v<version:\d+>/rest/<id:\d+>/<method:[\w_]+>' => 'rest/<method>',
  7. ),
  8.  
  9. /app/controller/restAction.php
  10. // [DELETE] http://www.billge.cc/v2/rest/123/person
  11. public function DELETE_person($version, $id)
  12. {
  13. echo $version; // 2
  14. echo $id; // 123
  15. }
  16. // [PUT] http://www.billge.cc/rest/272 正则匹配的内容会传入方法
  17. public function PUT_test($id)
  18. {
  19. echo $id; // 272
  20. }