Base.php 1.4 KB

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