InitMiddleware.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. declare (strict_types=1);
  15. namespace app\api\http\middleware;
  16. use app\common\exception\ControllerExtendException;
  17. use app\api\controller\BaseApiController;
  18. use think\exception\ClassNotFoundException;
  19. use think\exception\HttpException;
  20. class InitMiddleware
  21. {
  22. /**
  23. * @notes 初始化
  24. * @param $request
  25. * @param \Closure $next
  26. * @return mixed
  27. * @throws ControllerExtendException
  28. * @author 段誉
  29. * @date 2022/9/6 18:17
  30. */
  31. public function handle($request, \Closure $next)
  32. {
  33. //获取控制器
  34. try {
  35. $controller = str_replace('.', '\\', $request->controller());
  36. $controller = '\\app\\api\\controller\\' . $controller . 'Controller';
  37. $controllerClass = invoke($controller);
  38. if (($controllerClass instanceof BaseApiController) === false) {
  39. throw new ControllerExtendException($controller, '404');
  40. }
  41. } catch (ClassNotFoundException $e) {
  42. throw new HttpException(404, 'controller not exists:' . $e->getClass());
  43. }
  44. //创建控制器对象
  45. $request->controllerObject = invoke($controller);
  46. return $next($request);
  47. }
  48. }