App.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 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. declare (strict_types = 1);
  12. namespace think;
  13. use think\event\AppInit;
  14. use think\helper\Str;
  15. use think\initializer\BootService;
  16. use think\initializer\Error;
  17. use think\initializer\RegisterService;
  18. /**
  19. * App 基础类
  20. * @property Route $route
  21. * @property Config $config
  22. * @property Cache $cache
  23. * @property Request $request
  24. * @property Http $http
  25. * @property Console $console
  26. * @property Env $env
  27. * @property Event $event
  28. * @property Middleware $middleware
  29. * @property Log $log
  30. * @property Lang $lang
  31. * @property Db $db
  32. * @property Cookie $cookie
  33. * @property Session $session
  34. * @property Validate $validate
  35. * @property Filesystem $filesystem
  36. */
  37. class App extends Container
  38. {
  39. const VERSION = '6.0.0';
  40. /**
  41. * 应用调试模式
  42. * @var bool
  43. */
  44. protected $appDebug = false;
  45. /**
  46. * 应用开始时间
  47. * @var float
  48. */
  49. protected $beginTime;
  50. /**
  51. * 应用内存初始占用
  52. * @var integer
  53. */
  54. protected $beginMem;
  55. /**
  56. * 当前应用类库命名空间
  57. * @var string
  58. */
  59. protected $namespace = 'app';
  60. /**
  61. * 应用根目录
  62. * @var string
  63. */
  64. protected $rootPath = '';
  65. /**
  66. * 框架目录
  67. * @var string
  68. */
  69. protected $thinkPath = '';
  70. /**
  71. * 应用目录
  72. * @var string
  73. */
  74. protected $appPath = '';
  75. /**
  76. * Runtime目录
  77. * @var string
  78. */
  79. protected $runtimePath = '';
  80. /**
  81. * 路由定义目录
  82. * @var string
  83. */
  84. protected $routePath = '';
  85. /**
  86. * 配置后缀
  87. * @var string
  88. */
  89. protected $configExt = '.php';
  90. /**
  91. * 应用初始化器
  92. * @var array
  93. */
  94. protected $initializers = [
  95. Error::class,
  96. RegisterService::class,
  97. BootService::class,
  98. ];
  99. /**
  100. * 注册的系统服务
  101. * @var array
  102. */
  103. protected $services = [];
  104. /**
  105. * 初始化
  106. * @var bool
  107. */
  108. protected $initialized = false;
  109. /**
  110. * 容器绑定标识
  111. * @var array
  112. */
  113. protected $bind = [
  114. 'app' => App::class,
  115. 'cache' => Cache::class,
  116. 'config' => Config::class,
  117. 'console' => Console::class,
  118. 'cookie' => Cookie::class,
  119. 'db' => Db::class,
  120. 'env' => Env::class,
  121. 'event' => Event::class,
  122. 'http' => Http::class,
  123. 'lang' => Lang::class,
  124. 'log' => Log::class,
  125. 'middleware' => Middleware::class,
  126. 'request' => Request::class,
  127. 'response' => Response::class,
  128. 'route' => Route::class,
  129. 'session' => Session::class,
  130. 'validate' => Validate::class,
  131. 'view' => View::class,
  132. 'filesystem' => Filesystem::class,
  133. 'think\DbManager' => Db::class,
  134. 'think\LogManager' => Log::class,
  135. 'think\CacheManager' => Cache::class,
  136. // 接口依赖注入
  137. 'Psr\Log\LoggerInterface' => Log::class,
  138. ];
  139. /**
  140. * 架构方法
  141. * @access public
  142. * @param string $rootPath 应用根目录
  143. */
  144. public function __construct(string $rootPath = '')
  145. {
  146. $this->thinkPath = dirname(__DIR__) . DIRECTORY_SEPARATOR;
  147. $this->rootPath = $rootPath ? rtrim($rootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $this->getDefaultRootPath();
  148. $this->appPath = $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
  149. $this->runtimePath = $this->rootPath . 'runtime' . DIRECTORY_SEPARATOR;
  150. if (is_file($this->appPath . 'provider.php')) {
  151. $this->bind(include $this->appPath . 'provider.php');
  152. }
  153. static::setInstance($this);
  154. $this->instance('app', $this);
  155. $this->instance('think\Container', $this);
  156. }
  157. /**
  158. * 注册服务
  159. * @access public
  160. * @param Service|string $service 服务
  161. * @param bool $force 强制重新注册
  162. * @return Service|null
  163. */
  164. public function register($service, bool $force = false)
  165. {
  166. $registered = $this->getService($service);
  167. if ($registered && !$force) {
  168. return $registered;
  169. }
  170. if (is_string($service)) {
  171. $service = new $service($this);
  172. }
  173. if (method_exists($service, 'register')) {
  174. $service->register();
  175. }
  176. if (property_exists($service, 'bind')) {
  177. $this->bind($service->bind);
  178. }
  179. $this->services[] = $service;
  180. }
  181. /**
  182. * 执行服务
  183. * @access public
  184. * @param Service $service 服务
  185. * @return mixed
  186. */
  187. public function bootService($service)
  188. {
  189. if (method_exists($service, 'boot')) {
  190. return $this->invoke([$service, 'boot']);
  191. }
  192. }
  193. /**
  194. * 获取服务
  195. * @param string|Service $service
  196. * @return Service|null
  197. */
  198. public function getService($service)
  199. {
  200. $name = is_string($service) ? $service : get_class($service);
  201. return array_values(array_filter($this->services, function ($value) use ($name) {
  202. return $value instanceof $name;
  203. }, ARRAY_FILTER_USE_BOTH))[0] ?? null;
  204. }
  205. /**
  206. * 开启应用调试模式
  207. * @access public
  208. * @param bool $debug 开启应用调试模式
  209. * @return $this
  210. */
  211. public function debug(bool $debug = true)
  212. {
  213. $this->appDebug = $debug;
  214. return $this;
  215. }
  216. /**
  217. * 是否为调试模式
  218. * @access public
  219. * @return bool
  220. */
  221. public function isDebug(): bool
  222. {
  223. return $this->appDebug;
  224. }
  225. /**
  226. * 设置应用命名空间
  227. * @access public
  228. * @param string $namespace 应用命名空间
  229. * @return $this
  230. */
  231. public function setNamespace(string $namespace)
  232. {
  233. $this->namespace = $namespace;
  234. return $this;
  235. }
  236. /**
  237. * 获取应用类库命名空间
  238. * @access public
  239. * @return string
  240. */
  241. public function getNamespace(): string
  242. {
  243. return $this->namespace;
  244. }
  245. /**
  246. * 获取框架版本
  247. * @access public
  248. * @return string
  249. */
  250. public function version(): string
  251. {
  252. return static::VERSION;
  253. }
  254. /**
  255. * 获取应用根目录
  256. * @access public
  257. * @return string
  258. */
  259. public function getRootPath(): string
  260. {
  261. return $this->rootPath;
  262. }
  263. /**
  264. * 获取应用基础目录
  265. * @access public
  266. * @return string
  267. */
  268. public function getBasePath(): string
  269. {
  270. return $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
  271. }
  272. /**
  273. * 获取当前应用目录
  274. * @access public
  275. * @return string
  276. */
  277. public function getAppPath(): string
  278. {
  279. return $this->appPath;
  280. }
  281. /**
  282. * 设置应用目录
  283. * @param string $path 应用目录
  284. */
  285. public function setAppPath(string $path)
  286. {
  287. $this->appPath = $path;
  288. }
  289. /**
  290. * 获取应用运行时目录
  291. * @access public
  292. * @return string
  293. */
  294. public function getRuntimePath(): string
  295. {
  296. return $this->runtimePath;
  297. }
  298. /**
  299. * 设置runtime目录
  300. * @param string $path 定义目录
  301. */
  302. public function setRuntimePath(string $path): void
  303. {
  304. $this->runtimePath = $path;
  305. }
  306. /**
  307. * 获取核心框架目录
  308. * @access public
  309. * @return string
  310. */
  311. public function getThinkPath(): string
  312. {
  313. return $this->thinkPath;
  314. }
  315. /**
  316. * 获取应用配置目录
  317. * @access public
  318. * @return string
  319. */
  320. public function getConfigPath(): string
  321. {
  322. return $this->rootPath . 'config' . DIRECTORY_SEPARATOR;
  323. }
  324. /**
  325. * 获取配置后缀
  326. * @access public
  327. * @return string
  328. */
  329. public function getConfigExt(): string
  330. {
  331. return $this->configExt;
  332. }
  333. /**
  334. * 获取应用开启时间
  335. * @access public
  336. * @return float
  337. */
  338. public function getBeginTime(): float
  339. {
  340. return $this->beginTime;
  341. }
  342. /**
  343. * 获取应用初始内存占用
  344. * @access public
  345. * @return integer
  346. */
  347. public function getBeginMem(): int
  348. {
  349. return $this->beginMem;
  350. }
  351. /**
  352. * 初始化应用
  353. * @access public
  354. * @return $this
  355. */
  356. public function initialize()
  357. {
  358. $this->initialized = true;
  359. $this->beginTime = microtime(true);
  360. $this->beginMem = memory_get_usage();
  361. // 加载环境变量
  362. if (is_file($this->rootPath . '.env')) {
  363. $this->env->load($this->rootPath . '.env');
  364. }
  365. $this->configExt = $this->env->get('config_ext', '.php');
  366. $this->debugModeInit();
  367. // 加载全局初始化文件
  368. $this->load();
  369. // 加载框架默认语言包
  370. $langSet = $this->lang->defaultLangSet();
  371. $this->lang->load($this->thinkPath . 'lang' . DIRECTORY_SEPARATOR . $langSet . '.php');
  372. // 加载应用默认语言包
  373. $this->loadLangPack($langSet);
  374. // 监听AppInit
  375. $this->event->trigger(AppInit::class);
  376. date_default_timezone_set($this->config->get('app.default_timezone', 'Asia/Shanghai'));
  377. // 初始化
  378. foreach ($this->initializers as $initializer) {
  379. $this->make($initializer)->init($this);
  380. }
  381. return $this;
  382. }
  383. /**
  384. * 是否初始化过
  385. * @return bool
  386. */
  387. public function initialized()
  388. {
  389. return $this->initialized;
  390. }
  391. /**
  392. * 加载语言包
  393. * @param string $langset 语言
  394. * @return void
  395. */
  396. public function loadLangPack($langset)
  397. {
  398. if (empty($langset)) {
  399. return;
  400. }
  401. // 加载系统语言包
  402. $files = glob($this->appPath . 'lang' . DIRECTORY_SEPARATOR . $langset . '.*');
  403. $this->lang->load($files);
  404. // 加载扩展(自定义)语言包
  405. $list = $this->config->get('lang.extend_list', []);
  406. if (isset($list[$langset])) {
  407. $this->lang->load($list[$langset]);
  408. }
  409. }
  410. /**
  411. * 引导应用
  412. * @access public
  413. * @return void
  414. */
  415. public function boot(): void
  416. {
  417. array_walk($this->services, function ($service) {
  418. $this->bootService($service);
  419. });
  420. }
  421. /**
  422. * 加载应用文件和配置
  423. * @access protected
  424. * @return void
  425. */
  426. protected function load(): void
  427. {
  428. $appPath = $this->getAppPath();
  429. if (is_file($appPath . 'common.php')) {
  430. include_once $appPath . 'common.php';
  431. }
  432. include_once $this->thinkPath . 'helper.php';
  433. $configPath = $this->getConfigPath();
  434. $files = [];
  435. if (is_dir($configPath)) {
  436. $files = glob($configPath . '*' . $this->configExt);
  437. }
  438. foreach ($files as $file) {
  439. $this->config->load($file, pathinfo($file, PATHINFO_FILENAME));
  440. }
  441. if (is_file($appPath . 'event.php')) {
  442. $this->loadEvent(include $appPath . 'event.php');
  443. }
  444. if (is_file($appPath . 'service.php')) {
  445. $services = include $appPath . 'service.php';
  446. foreach ($services as $service) {
  447. $this->register($service);
  448. }
  449. }
  450. }
  451. /**
  452. * 调试模式设置
  453. * @access protected
  454. * @return void
  455. */
  456. protected function debugModeInit(): void
  457. {
  458. // 应用调试模式
  459. if (!$this->appDebug) {
  460. $this->appDebug = $this->env->get('app_debug') ? true : false;
  461. ini_set('display_errors', 'Off');
  462. }
  463. if (!$this->runningInConsole()) {
  464. //重新申请一块比较大的buffer
  465. if (ob_get_level() > 0) {
  466. $output = ob_get_clean();
  467. }
  468. ob_start();
  469. if (!empty($output)) {
  470. echo $output;
  471. }
  472. }
  473. }
  474. /**
  475. * 注册应用事件
  476. * @access protected
  477. * @param array $event 事件数据
  478. * @return void
  479. */
  480. public function loadEvent(array $event): void
  481. {
  482. if (isset($event['bind'])) {
  483. $this->event->bind($event['bind']);
  484. }
  485. if (isset($event['listen'])) {
  486. $this->event->listenEvents($event['listen']);
  487. }
  488. if (isset($event['subscribe'])) {
  489. $this->event->subscribe($event['subscribe']);
  490. }
  491. }
  492. /**
  493. * 解析应用类的类名
  494. * @access public
  495. * @param string $layer 层名 controller model ...
  496. * @param string $name 类名
  497. * @return string
  498. */
  499. public function parseClass(string $layer, string $name): string
  500. {
  501. $name = str_replace(['/', '.'], '\\', $name);
  502. $array = explode('\\', $name);
  503. $class = Str::studly(array_pop($array));
  504. $path = $array ? implode('\\', $array) . '\\' : '';
  505. return $this->namespace . '\\' . $layer . '\\' . $path . $class;
  506. }
  507. /**
  508. * 是否运行在命令行下
  509. * @return bool
  510. */
  511. public function runningInConsole()
  512. {
  513. return php_sapi_name() === 'cli' || php_sapi_name() === 'phpdbg';
  514. }
  515. /**
  516. * 获取应用根目录
  517. * @access protected
  518. * @return string
  519. */
  520. protected function getDefaultRootPath(): string
  521. {
  522. $path = dirname(dirname(dirname(dirname($this->thinkPath))));
  523. return $path . DIRECTORY_SEPARATOR;
  524. }
  525. }