BaseController.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. declare (strict_types=1);
  3. namespace app;
  4. use think\App;
  5. use think\exception\ValidateException;
  6. use think\Validate;
  7. /**
  8. * 控制器基础类
  9. */
  10. abstract class BaseController
  11. {
  12. /**
  13. * Request实例
  14. * @var \think\Request
  15. */
  16. protected $request;
  17. /**
  18. * 应用实例
  19. * @var App
  20. */
  21. protected $app;
  22. /**
  23. * 是否批量验证
  24. * @var bool
  25. */
  26. protected $batchValidate = false;
  27. /**
  28. * 控制器中间件
  29. * @var array
  30. */
  31. protected $middleware = [];
  32. /**
  33. * 构造方法
  34. * @access public
  35. * @param App $app 应用对象
  36. */
  37. public function __construct(App $app)
  38. {
  39. $this->app = $app;
  40. $this->request = $this->app->request;
  41. $this->request->controllerPath = str_replace('.', '/', $this->request->controller(true));
  42. // 控制器初始化
  43. $this->initialize();
  44. }
  45. // 初始化
  46. protected function initialize()
  47. {
  48. }
  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();
  79. }
  80. return $v->failException()->check($data);
  81. }
  82. }