BaseController.php 2.1 KB

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