App.php 20 KB

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