Route.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace think\addons;
  3. use think\Config;
  4. use think\exception\HttpException;
  5. use think\exception\HttpResponseException;
  6. use think\Hook;
  7. use think\Loader;
  8. use think\Request;
  9. use think\Response;
  10. /**
  11. * 插件执行默认控制器
  12. * @package think\addons
  13. */
  14. class Route
  15. {
  16. /**
  17. * 插件执行
  18. */
  19. public function execute($addon = null, $controller = null, $action = null)
  20. {
  21. $request = Request::instance();
  22. // 是否自动转换控制器和操作名
  23. $convert = Config::get('url_convert');
  24. $filter = $convert ? 'strtolower' : 'trim';
  25. $addon = $addon ? trim(call_user_func($filter, $addon)) : '';
  26. $controller = $controller ? trim(call_user_func($filter, $controller)) : 'index';
  27. $action = $action ? trim(call_user_func($filter, $action)) : 'index';
  28. Hook::listen('addon_begin', $request);
  29. if (!empty($addon) && !empty($controller) && !empty($action)) {
  30. $info = get_addon_info($addon);
  31. if (!$info) {
  32. throw new HttpException(404, __('addon %s not found', $addon));
  33. }
  34. if (!$info['state']) {
  35. throw new HttpException(500, __('addon %s is disabled', $addon));
  36. }
  37. $dispatch = $request->dispatch();
  38. if (isset($dispatch['var']) && $dispatch['var']) {
  39. $request->route(array_diff_key($dispatch['var'], array_flip(['addon', 'controller', 'action'])));
  40. }
  41. // 设置当前请求的控制器、操作
  42. $request->controller($controller)->action($action);
  43. // 监听addon_module_init
  44. Hook::listen('addon_module_init', $request);
  45. // 兼容旧版本行为,即将移除,不建议使用
  46. Hook::listen('addons_init', $request);
  47. $class = get_addon_class($addon, 'controller', $controller);
  48. if (!$class) {
  49. throw new HttpException(404, __('addon controller %s not found', Loader::parseName($controller, 1)));
  50. }
  51. $instance = new $class($request);
  52. $vars = [];
  53. if (is_callable([$instance, $action])) {
  54. // 执行操作方法
  55. $call = [$instance, $action];
  56. } elseif (is_callable([$instance, '_empty'])) {
  57. // 空操作
  58. $call = [$instance, '_empty'];
  59. $vars = [$action];
  60. } else {
  61. // 操作不存在
  62. throw new HttpException(404, __('addon action %s not found', get_class($instance) . '->' . $action . '()'));
  63. }
  64. Hook::listen('addon_action_begin', $call);
  65. return call_user_func_array($call, $vars);
  66. } else {
  67. abort(500, lang('addon can not be empty'));
  68. }
  69. }
  70. }