Brak opisu
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BaseController.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. }