Result.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace app\common\util;
  3. use think\Model;
  4. /**
  5. * 通用返回值
  6. */
  7. class Result
  8. {
  9. /**
  10. * $code 业务码
  11. *
  12. * @var mixed
  13. */
  14. protected $code = -1;
  15. /**
  16. * $data 数据
  17. *
  18. * @var mixed
  19. */
  20. protected $data;
  21. /**
  22. * $msg 提示消息
  23. *
  24. * @var string
  25. */
  26. protected $msg = 'Never init error';
  27. public function __construct($data, $code = 0, $msg = '')
  28. {
  29. $this->code = $code;
  30. $this->data = $data;
  31. $this->msg = $msg;
  32. }
  33. public static function of($data, $code = 0, $msg = 'success')
  34. {
  35. return new Result($data, $code, $msg);
  36. }
  37. public static function success()
  38. {
  39. return new Result(null, 0, 'success');
  40. }
  41. public static function failed($code = -1, $msg = 'failed')
  42. {
  43. return new Result(null, $code, $msg);
  44. }
  45. public function toArray() {
  46. return [
  47. 'code' => $this->code,
  48. 'msg' => $this->msg,
  49. 'data' => $this->data,
  50. ];
  51. }
  52. /**
  53. * 生成 Http Json Result 数据
  54. *
  55. * @param mixed $data
  56. * @param int $code
  57. * @param string $msg
  58. *
  59. * @return \think\Response\Json
  60. */
  61. public static function rest($data = null, $code = 0, $msg = 'success')
  62. {
  63. return json(self::of($data, $code, $msg)->toArray());
  64. }
  65. /**
  66. * 生成 Http Json Result 失败的数据
  67. *
  68. * @param int $code
  69. * @param string $msg
  70. *
  71. * @return \think\Response\Json
  72. */
  73. public static function restf($code, $msg)
  74. {
  75. return self::rest(null, $code, $msg);
  76. }
  77. }