BaseController.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\common;
  4. use support\lib\Instance;
  5. use think\App;
  6. use think\cache\driver\Redis;
  7. use think\exception\ValidateException;
  8. use think\Validate;
  9. /**
  10. * 控制器基础类
  11. */
  12. abstract class BaseController
  13. {
  14. /**
  15. * Request实例
  16. * @var \think\Request
  17. */
  18. protected $request;
  19. /**
  20. * 应用实例
  21. * @var \think\App
  22. */
  23. //protected $app;
  24. /**
  25. * 是否批量验证
  26. * @var bool
  27. */
  28. protected $batchValidate = false;
  29. /**
  30. * 控制器中间件
  31. * @var array
  32. */
  33. protected $middleware = [
  34. 'app\middleware\Api' => ['except' => ['login','createUser','refresh','hello']],//不需要鉴权的接口
  35. ];
  36. /**
  37. * @var Redis|null
  38. */
  39. protected $redis = null;
  40. /**
  41. * 构造方法
  42. * @access public
  43. * @param App $app 应用对象
  44. */
  45. public function __construct()
  46. {
  47. header('Access-Control-Allow-Origin: *');
  48. header('Access-Control-Allow-Credentials: true');
  49. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  50. header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId,Host,Referer");
  51. // 控制器初始化
  52. $this->initialize();
  53. //单列redis
  54. $this->redis = \app\common\Redis::getRedis();
  55. }
  56. // 初始化
  57. protected function initialize()
  58. {}
  59. /**
  60. * 验证数据
  61. * @access protected
  62. * @param array $data 数据
  63. * @param string|array $validate 验证器名或者验证规则数组
  64. * @param array $message 提示信息
  65. * @param bool $batch 是否批量验证
  66. * @return array|string|true
  67. * @throws ValidateException
  68. */
  69. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  70. {
  71. if (is_array($validate)) {
  72. $v = new Validate();
  73. $v->rule($validate);
  74. } else {
  75. if (strpos($validate, '.')) {
  76. // 支持场景
  77. [$validate, $scene] = explode('.', $validate);
  78. }
  79. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  80. $v = new $class();
  81. if (!empty($scene)) {
  82. $v->scene($scene);
  83. }
  84. }
  85. $v->message($message);
  86. // 是否批量验证
  87. if ($batch || $this->batchValidate) {
  88. $v->batch(true);
  89. }
  90. return $v->failException(true)->check($data);
  91. }
  92. }