Route.php 2.6 KB

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