App.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\exception\HttpException;
  13. use think\exception\HttpResponseException;
  14. use think\exception\RouteNotFoundException;
  15. /**
  16. * App 应用管理
  17. * @author liu21st <liu21st@gmail.com>
  18. */
  19. class App
  20. {
  21. /**
  22. * @var bool 是否初始化过
  23. */
  24. protected static $init = false;
  25. /**
  26. * @var string 当前模块路径
  27. */
  28. public static $modulePath;
  29. /**
  30. * @var bool 应用调试模式
  31. */
  32. public static $debug = true;
  33. /**
  34. * @var string 应用类库命名空间
  35. */
  36. public static $namespace = 'app';
  37. /**
  38. * @var bool 应用类库后缀
  39. */
  40. public static $suffix = false;
  41. /**
  42. * @var bool 应用路由检测
  43. */
  44. protected static $routeCheck;
  45. /**
  46. * @var bool 严格路由检测
  47. */
  48. protected static $routeMust;
  49. protected static $dispatch;
  50. protected static $file = [];
  51. /**
  52. * 执行应用程序
  53. * @access public
  54. * @param Request $request Request对象
  55. * @return Response
  56. * @throws Exception
  57. */
  58. public static function run(Request $request = null)
  59. {
  60. is_null($request) && $request = Request::instance();
  61. try {
  62. $config = self::initCommon();
  63. if (defined('BIND_MODULE')) {
  64. // 模块/控制器绑定
  65. BIND_MODULE && Route::bind(BIND_MODULE);
  66. } elseif ($config['auto_bind_module']) {
  67. // 入口自动绑定
  68. $name = pathinfo($request->baseFile(), PATHINFO_FILENAME);
  69. if ($name && 'index' != $name && is_dir(APP_PATH . $name)) {
  70. Route::bind($name);
  71. }
  72. }
  73. $request->filter($config['default_filter']);
  74. if ($config['lang_switch_on']) {
  75. // 开启多语言机制 检测当前语言
  76. Lang::detect();
  77. } else {
  78. // 读取默认语言
  79. Lang::range($config['default_lang']);
  80. }
  81. $request->langset(Lang::range());
  82. // 加载系统语言包
  83. Lang::load([
  84. THINK_PATH . 'lang' . DS . $request->langset() . EXT,
  85. APP_PATH . 'lang' . DS . $request->langset() . EXT,
  86. ]);
  87. // 获取应用调度信息
  88. $dispatch = self::$dispatch;
  89. if (empty($dispatch)) {
  90. // 进行URL路由检测
  91. $dispatch = self::routeCheck($request, $config);
  92. }
  93. // 记录当前调度信息
  94. $request->dispatch($dispatch);
  95. // 记录路由和请求信息
  96. if (self::$debug) {
  97. Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info');
  98. Log::record('[ HEADER ] ' . var_export($request->header(), true), 'info');
  99. Log::record('[ PARAM ] ' . var_export($request->param(), true), 'info');
  100. }
  101. // 监听app_begin
  102. Hook::listen('app_begin', $dispatch);
  103. // 请求缓存检查
  104. $request->cache($config['request_cache'], $config['request_cache_expire']);
  105. switch ($dispatch['type']) {
  106. case 'redirect':
  107. // 执行重定向跳转
  108. $data = Response::create($dispatch['url'], 'redirect')->code($dispatch['status']);
  109. break;
  110. case 'module':
  111. // 模块/控制器/操作
  112. $data = self::module($dispatch['module'], $config, isset($dispatch['convert']) ? $dispatch['convert'] : null);
  113. break;
  114. case 'controller':
  115. // 执行控制器操作
  116. $vars = array_merge(Request::instance()->param(), $dispatch['var']);
  117. $data = Loader::action($dispatch['controller'], $vars, $config['url_controller_layer'], $config['controller_suffix']);
  118. break;
  119. case 'method':
  120. // 执行回调方法
  121. $vars = array_merge(Request::instance()->param(), $dispatch['var']);
  122. $data = self::invokeMethod($dispatch['method'], $vars);
  123. break;
  124. case 'function':
  125. // 执行闭包
  126. $data = self::invokeFunction($dispatch['function']);
  127. break;
  128. case 'response':
  129. $data = $dispatch['response'];
  130. break;
  131. default:
  132. throw new \InvalidArgumentException('dispatch type not support');
  133. }
  134. } catch (HttpResponseException $exception) {
  135. $data = $exception->getResponse();
  136. }
  137. // 清空类的实例化
  138. Loader::clearInstance();
  139. // 输出数据到客户端
  140. if ($data instanceof Response) {
  141. $response = $data;
  142. } elseif (!is_null($data)) {
  143. // 默认自动识别响应输出类型
  144. $isAjax = $request->isAjax();
  145. $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type');
  146. $response = Response::create($data, $type);
  147. } else {
  148. $response = Response::create();
  149. }
  150. // 监听app_end
  151. Hook::listen('app_end', $response);
  152. return $response;
  153. }
  154. /**
  155. * 设置当前请求的调度信息
  156. * @access public
  157. * @param array|string $dispatch 调度信息
  158. * @param string $type 调度类型
  159. * @return void
  160. */
  161. public static function dispatch($dispatch, $type = 'module')
  162. {
  163. self::$dispatch = ['type' => $type, $type => $dispatch];
  164. }
  165. /**
  166. * 执行函数或者闭包方法 支持参数调用
  167. * @access public
  168. * @param string|array|\Closure $function 函数或者闭包
  169. * @param array $vars 变量
  170. * @return mixed
  171. */
  172. public static function invokeFunction($function, $vars = [])
  173. {
  174. $reflect = new \ReflectionFunction($function);
  175. $args = self::bindParams($reflect, $vars);
  176. // 记录执行信息
  177. self::$debug && Log::record('[ RUN ] ' . $reflect->__toString(), 'info');
  178. return $reflect->invokeArgs($args);
  179. }
  180. /**
  181. * 调用反射执行类的方法 支持参数绑定
  182. * @access public
  183. * @param string|array $method 方法
  184. * @param array $vars 变量
  185. * @return mixed
  186. */
  187. public static function invokeMethod($method, $vars = [])
  188. {
  189. if (is_array($method)) {
  190. $class = is_object($method[0]) ? $method[0] : self::invokeClass($method[0]);
  191. $reflect = new \ReflectionMethod($class, $method[1]);
  192. } else {
  193. // 静态方法
  194. $reflect = new \ReflectionMethod($method);
  195. }
  196. $args = self::bindParams($reflect, $vars);
  197. self::$debug && Log::record('[ RUN ] ' . $reflect->class . '->' . $reflect->name . '[ ' . $reflect->getFileName() . ' ]', 'info');
  198. return $reflect->invokeArgs(isset($class) ? $class : null, $args);
  199. }
  200. /**
  201. * 调用反射执行类的实例化 支持依赖注入
  202. * @access public
  203. * @param string $class 类名
  204. * @param array $vars 变量
  205. * @return mixed
  206. */
  207. public static function invokeClass($class, $vars = [])
  208. {
  209. $reflect = new \ReflectionClass($class);
  210. $constructor = $reflect->getConstructor();
  211. if ($constructor) {
  212. $args = self::bindParams($constructor, $vars);
  213. } else {
  214. $args = [];
  215. }
  216. return $reflect->newInstanceArgs($args);
  217. }
  218. /**
  219. * 绑定参数
  220. * @access public
  221. * @param \ReflectionMethod|\ReflectionFunction $reflect 反射类
  222. * @param array $vars 变量
  223. * @return array
  224. */
  225. private static function bindParams($reflect, $vars = [])
  226. {
  227. if (empty($vars)) {
  228. // 自动获取请求变量
  229. if (Config::get('url_param_type')) {
  230. $vars = Request::instance()->route();
  231. } else {
  232. $vars = Request::instance()->param();
  233. }
  234. }
  235. $args = [];
  236. // 判断数组类型 数字数组时按顺序绑定参数
  237. reset($vars);
  238. $type = key($vars) === 0 ? 1 : 0;
  239. if ($reflect->getNumberOfParameters() > 0) {
  240. $params = $reflect->getParameters();
  241. foreach ($params as $param) {
  242. $name = $param->getName();
  243. $class = $param->getClass();
  244. if ($class) {
  245. $className = $class->getName();
  246. $bind = Request::instance()->$name;
  247. if ($bind instanceof $className) {
  248. $args[] = $bind;
  249. } else {
  250. if (method_exists($className, 'invoke')) {
  251. $method = new \ReflectionMethod($className, 'invoke');
  252. if ($method->isPublic() && $method->isStatic()) {
  253. $args[] = $className::invoke(Request::instance());
  254. continue;
  255. }
  256. }
  257. $args[] = method_exists($className, 'instance') ? $className::instance() : new $className;
  258. }
  259. } elseif (1 == $type && !empty($vars)) {
  260. $args[] = array_shift($vars);
  261. } elseif (0 == $type && isset($vars[$name])) {
  262. $args[] = $vars[$name];
  263. } elseif ($param->isDefaultValueAvailable()) {
  264. $args[] = $param->getDefaultValue();
  265. } else {
  266. throw new \InvalidArgumentException('method param miss:' . $name);
  267. }
  268. }
  269. }
  270. return $args;
  271. }
  272. /**
  273. * 执行模块
  274. * @access public
  275. * @param array $result 模块/控制器/操作
  276. * @param array $config 配置参数
  277. * @param bool $convert 是否自动转换控制器和操作名
  278. * @return mixed
  279. */
  280. public static function module($result, $config, $convert = null)
  281. {
  282. if (is_string($result)) {
  283. $result = explode('/', $result);
  284. }
  285. $request = Request::instance();
  286. if ($config['app_multi_module']) {
  287. // 多模块部署
  288. $module = strip_tags(strtolower($result[0] ?: $config['default_module']));
  289. $bind = Route::getBind('module');
  290. $available = false;
  291. if ($bind) {
  292. // 绑定模块
  293. list($bindModule) = explode('/', $bind);
  294. if (empty($result[0])) {
  295. $module = $bindModule;
  296. $available = true;
  297. } elseif ($module == $bindModule) {
  298. $available = true;
  299. }
  300. } elseif (!in_array($module, $config['deny_module_list']) && is_dir(APP_PATH . $module)) {
  301. $available = true;
  302. }
  303. // 模块初始化
  304. if ($module && $available) {
  305. // 初始化模块
  306. $request->module($module);
  307. $config = self::init($module);
  308. // 模块请求缓存检查
  309. $request->cache($config['request_cache'], $config['request_cache_expire']);
  310. } else {
  311. throw new HttpException(404, 'module not exists:' . $module);
  312. }
  313. } else {
  314. // 单一模块部署
  315. $module = '';
  316. $request->module($module);
  317. }
  318. // 当前模块路径
  319. App::$modulePath = APP_PATH . ($module ? $module . DS : '');
  320. // 是否自动转换控制器和操作名
  321. $convert = is_bool($convert) ? $convert : $config['url_convert'];
  322. // 获取控制器名
  323. $controller = strip_tags($result[1] ?: $config['default_controller']);
  324. $controller = $convert ? strtolower($controller) : $controller;
  325. // 获取操作名
  326. $actionName = strip_tags($result[2] ?: $config['default_action']);
  327. $actionName = $convert ? strtolower($actionName) : $actionName;
  328. // 设置当前请求的控制器、操作
  329. $request->controller(Loader::parseName($controller, 1))->action($actionName);
  330. // 监听module_init
  331. Hook::listen('module_init', $request);
  332. $instance = Loader::controller($controller, $config['url_controller_layer'], $config['controller_suffix'], $config['empty_controller']);
  333. if (is_null($instance)) {
  334. throw new HttpException(404, 'controller not exists:' . Loader::parseName($controller, 1));
  335. }
  336. // 获取当前操作名
  337. $action = $actionName . $config['action_suffix'];
  338. $vars = [];
  339. if (is_callable([$instance, $action])) {
  340. // 执行操作方法
  341. $call = [$instance, $action];
  342. } elseif (is_callable([$instance, '_empty'])) {
  343. // 空操作
  344. $call = [$instance, '_empty'];
  345. $vars = [$actionName];
  346. } else {
  347. // 操作不存在
  348. throw new HttpException(404, 'method not exists:' . get_class($instance) . '->' . $action . '()');
  349. }
  350. Hook::listen('action_begin', $call);
  351. return self::invokeMethod($call, $vars);
  352. }
  353. /**
  354. * 初始化应用
  355. */
  356. public static function initCommon()
  357. {
  358. if (empty(self::$init)) {
  359. // 初始化应用
  360. $config = self::init();
  361. self::$suffix = $config['class_suffix'];
  362. // 应用调试模式
  363. self::$debug = Env::get('app_debug', Config::get('app_debug'));
  364. if (!self::$debug) {
  365. ini_set('display_errors', 'Off');
  366. } elseif (!IS_CLI) {
  367. //重新申请一块比较大的buffer
  368. if (ob_get_level() > 0) {
  369. $output = ob_get_clean();
  370. }
  371. ob_start();
  372. if (!empty($output)) {
  373. echo $output;
  374. }
  375. }
  376. // 注册应用命名空间
  377. self::$namespace = $config['app_namespace'];
  378. Loader::addNamespace($config['app_namespace'], APP_PATH);
  379. if (!empty($config['root_namespace'])) {
  380. Loader::addNamespace($config['root_namespace']);
  381. }
  382. // 加载额外文件
  383. if (!empty($config['extra_file_list'])) {
  384. foreach ($config['extra_file_list'] as $file) {
  385. $file = strpos($file, '.') ? $file : APP_PATH . $file . EXT;
  386. if (is_file($file) && !isset(self::$file[$file])) {
  387. include $file;
  388. self::$file[$file] = true;
  389. }
  390. }
  391. }
  392. // 设置系统时区
  393. date_default_timezone_set($config['default_timezone']);
  394. // 监听app_init
  395. Hook::listen('app_init');
  396. self::$init = true;
  397. }
  398. return Config::get();
  399. }
  400. /**
  401. * 初始化应用或模块
  402. * @access public
  403. * @param string $module 模块名
  404. * @return array
  405. */
  406. private static function init($module = '')
  407. {
  408. // 定位模块目录
  409. $module = $module ? $module . DS : '';
  410. // 加载初始化文件
  411. if (is_file(APP_PATH . $module . 'init' . EXT)) {
  412. include APP_PATH . $module . 'init' . EXT;
  413. } elseif (is_file(RUNTIME_PATH . $module . 'init' . EXT)) {
  414. include RUNTIME_PATH . $module . 'init' . EXT;
  415. } else {
  416. $path = APP_PATH . $module;
  417. // 加载模块配置
  418. $config = Config::load(CONF_PATH . $module . 'config' . CONF_EXT);
  419. // 读取数据库配置文件
  420. $filename = CONF_PATH . $module . 'database' . CONF_EXT;
  421. Config::load($filename, 'database');
  422. // 读取扩展配置文件
  423. if (is_dir(CONF_PATH . $module . 'extra')) {
  424. $dir = CONF_PATH . $module . 'extra';
  425. $files = scandir($dir);
  426. foreach ($files as $file) {
  427. if (strpos($file, CONF_EXT)) {
  428. $filename = $dir . DS . $file;
  429. Config::load($filename, pathinfo($file, PATHINFO_FILENAME));
  430. }
  431. }
  432. }
  433. // 加载应用状态配置
  434. if ($config['app_status']) {
  435. $config = Config::load(CONF_PATH . $module . $config['app_status'] . CONF_EXT);
  436. }
  437. // 加载行为扩展文件
  438. if (is_file(CONF_PATH . $module . 'tags' . EXT)) {
  439. Hook::import(include CONF_PATH . $module . 'tags' . EXT);
  440. }
  441. // 加载公共文件
  442. if (is_file($path . 'common' . EXT)) {
  443. include $path . 'common' . EXT;
  444. }
  445. // 加载当前模块语言包
  446. if ($module) {
  447. Lang::load($path . 'lang' . DS . Request::instance()->langset() . EXT);
  448. }
  449. }
  450. return Config::get();
  451. }
  452. /**
  453. * URL路由检测(根据PATH_INFO)
  454. * @access public
  455. * @param \think\Request $request
  456. * @param array $config
  457. * @return array
  458. * @throws \think\Exception
  459. */
  460. public static function routeCheck($request, array $config)
  461. {
  462. $path = $request->path();
  463. $depr = $config['pathinfo_depr'];
  464. $result = false;
  465. // 路由检测
  466. $check = !is_null(self::$routeCheck) ? self::$routeCheck : $config['url_route_on'];
  467. if ($check) {
  468. // 开启路由
  469. if (is_file(RUNTIME_PATH . 'route.php')) {
  470. // 读取路由缓存
  471. $rules = include RUNTIME_PATH . 'route.php';
  472. if (is_array($rules)) {
  473. Route::rules($rules);
  474. }
  475. } else {
  476. $files = $config['route_config_file'];
  477. foreach ($files as $file) {
  478. if (is_file(CONF_PATH . $file . CONF_EXT)) {
  479. // 导入路由配置
  480. $rules = include CONF_PATH . $file . CONF_EXT;
  481. if (is_array($rules)) {
  482. Route::import($rules);
  483. }
  484. }
  485. }
  486. }
  487. // 路由检测(根据路由定义返回不同的URL调度)
  488. $result = Route::check($request, $path, $depr, $config['url_domain_deploy']);
  489. $must = !is_null(self::$routeMust) ? self::$routeMust : $config['url_route_must'];
  490. if ($must && false === $result) {
  491. // 路由无效
  492. throw new RouteNotFoundException();
  493. }
  494. }
  495. if (false === $result) {
  496. // 路由无效 解析模块/控制器/操作/参数... 支持控制器自动搜索
  497. $result = Route::parseUrl($path, $depr, $config['controller_auto_search']);
  498. }
  499. return $result;
  500. }
  501. /**
  502. * 设置应用的路由检测机制
  503. * @access public
  504. * @param bool $route 是否需要检测路由
  505. * @param bool $must 是否强制检测路由
  506. * @return void
  507. */
  508. public static function route($route, $must = false)
  509. {
  510. self::$routeCheck = $route;
  511. self::$routeMust = $must;
  512. }
  513. }