BaseController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app;
  4. use app\controller\ResponseJson;
  5. use think\App;
  6. use think\exception\ValidateException;
  7. use think\Validate;
  8. /**
  9. * 控制器基础类
  10. */
  11. abstract class BaseController
  12. {
  13. /**
  14. * Request实例
  15. * @var \think\Request
  16. */
  17. protected $request;
  18. /**
  19. * 应用实例
  20. * @var \think\App
  21. */
  22. protected $app;
  23. /**
  24. * 是否批量验证
  25. * @var bool
  26. */
  27. protected $batchValidate = false;
  28. /**
  29. * 控制器中间件
  30. * @var array
  31. */
  32. protected $middleware = [];
  33. /**
  34. * 构造方法
  35. * @access public
  36. * @param App $app 应用对象
  37. */
  38. public function __construct(App $app)
  39. {
  40. $this->app = $app;
  41. $this->request = $this->app->request;
  42. // 控制器初始化
  43. $this->initialize();
  44. }
  45. // 初始化
  46. protected function initialize()
  47. {}
  48. use ResponseJson;
  49. /**
  50. * 验证数据
  51. * @access protected
  52. * @param array $data 数据
  53. * @param string|array $validate 验证器名或者验证规则数组
  54. * @param array $message 提示信息
  55. * @param bool $batch 是否批量验证
  56. * @return array|string|true
  57. * @throws ValidateException
  58. */
  59. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  60. {
  61. if (is_array($validate)) {
  62. $v = new Validate();
  63. $v->rule($validate);
  64. } else {
  65. if (strpos($validate, '.')) {
  66. // 支持场景
  67. [$validate, $scene] = explode('.', $validate);
  68. }
  69. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  70. $v = new $class();
  71. if (!empty($scene)) {
  72. $v->scene($scene);
  73. }
  74. }
  75. $v->message($message);
  76. // 是否批量验证
  77. if ($batch || $this->batchValidate) {
  78. $v->batch(true);
  79. }
  80. return $v->failException(true)->check($data);
  81. }
  82. protected function uuid()
  83. {
  84. // $uuid = substr ( $chars, 0, 8 ) . '-'
  85. // . substr ( $chars, 8, 4 ) . '-'
  86. // . substr ( $chars, 12, 4 ) . '-'
  87. // . substr ( $chars, 16, 4 ) . '-'
  88. // . substr ( $chars, 20, 12 );
  89. return md5(uniqid((string)mt_rand(), true));
  90. }
  91. }