App.php 14 KB

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