Base.php 1.4 KB

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