Base.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\api\controller;
  4. use think\App;
  5. use think\exception\HttpResponseException;
  6. use think\Response;
  7. use app\BaseController;
  8. class Base extends BaseController
  9. {
  10. public function __construct(App $app) {
  11. parent::__construct($app);
  12. }
  13. /**
  14. * @param string $message
  15. * @param int $code
  16. * @param null $data
  17. */
  18. public function error($message='',$code=1003,$data=null){
  19. $this->result($message,$data,$code);
  20. }
  21. /**
  22. * @param string $message
  23. * @param int $code
  24. * @param null $data
  25. */
  26. public function success($message='',$data=null,$code=0){
  27. $this->result($message,$data,$code);
  28. }
  29. /**
  30. * @param string $msg
  31. * @param null $data
  32. * @param int $code
  33. * @param string|null $type
  34. * @param array $header
  35. * @param array $options
  36. */
  37. private function result(string $msg, $data = null, int $code = 0, string $type = 'json', array $header = [], array
  38. $options = [])
  39. {
  40. $result = [
  41. 'code' => $code,
  42. 'message' => $msg,
  43. 'data' => $data,
  44. ];
  45. $code = 200;
  46. if (isset($header['statuscode'])) {
  47. $code = $header['statuscode'];
  48. unset($header['statuscode']);
  49. }
  50. $response = Response::create($result, $type, $code)->header($header)->options($options);
  51. throw new HttpResponseException($response);
  52. }
  53. }