BaseResponse.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <?php
  2. /**
  3. * 统一返回处理类(ajax)允许跨域
  4. *
  5. * 使用: **
  6. * use Gucci\ServerResponse;
  7. * return ServerResponse::createBySuccess("成功");
  8. * ServerResponse::createByError("断点失败了");
  9. */
  10. namespace app\common\base\response;
  11. use think\Response;
  12. abstract class BaseResponse
  13. {
  14. protected $code = 0;
  15. protected $msg = '';
  16. protected $error = null;
  17. protected $data = null;
  18. public function __construct($model){
  19. $this->beforeInit($model);
  20. $this->zskkInit($model);
  21. $this->afterInit($model);
  22. }
  23. protected function beforeInit($model) {}
  24. protected function afterInit($model) {}
  25. protected function zskkInit($model) {
  26. if(is_null($model)) {
  27. return;
  28. }
  29. if(isset($model->code)) {
  30. $this->setCode($model->code);
  31. }
  32. if(isset($model->msg)) {
  33. $this->setMsg($model->msg);
  34. }
  35. if(isset($model->data)) {
  36. $this->setData($model->data);
  37. }
  38. if(isset($model->error)) {
  39. $this->setError($model->error);
  40. }
  41. }
  42. public function setData($data)
  43. {
  44. $this->data = $data;
  45. return $this;
  46. }
  47. /**
  48. * @return null
  49. */
  50. public function getData()
  51. {
  52. return $this->data;
  53. }
  54. /**
  55. * @param null $error
  56. */
  57. public function setError($error): void
  58. {
  59. $this->error = $error;
  60. }
  61. /**
  62. * @return null
  63. */
  64. public function getError()
  65. {
  66. return $this->error;
  67. }
  68. public function setMsg(string $msg)
  69. {
  70. $this->msg = $msg;
  71. return $this;
  72. }
  73. /**
  74. * @return string
  75. */
  76. public function getMsg(): string
  77. {
  78. return $this->msg;
  79. }
  80. /**
  81. * @param int $code
  82. */
  83. public function setCode(int $code)
  84. {
  85. $this->code = $code;
  86. return $this;
  87. }
  88. /**
  89. * @return int
  90. */
  91. public function getCode(): int
  92. {
  93. return $this->code;
  94. }
  95. protected function setResponse($code = 0, $msg = '', $data = null, $error = null) {
  96. $this->setCode($code);
  97. $this->setMsg($msg);
  98. $this->setData($data);
  99. $this->setError($error);
  100. return $this;
  101. }
  102. protected function generateResponse() {
  103. return [
  104. "code" => $this->getCode(),
  105. "msg" => $this->getMsg(),
  106. "data" => $this->getData(),
  107. "error" => $this->getError(),
  108. ];
  109. }
  110. }