No Description

BaseController.php 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 \think\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. // 控制器初始化
  42. $this->initialize();
  43. }
  44. // 初始化
  45. protected function initialize()
  46. {}
  47. /**
  48. * 验证数据
  49. * @access protected
  50. * @param array $data 数据
  51. * @param string|array $validate 验证器名或者验证规则数组
  52. * @param array $message 提示信息
  53. * @param bool $batch 是否批量验证
  54. * @return array|string|true
  55. * @throws ValidateException
  56. */
  57. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  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 = false !== strpos($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(true);
  77. }
  78. return $v->failException(true)->check($data);
  79. }
  80. }