Application.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. /**
  10. * Application is the base class for all application classes.
  11. *
  12. * For more details and usage information on Application, see the [guide article on applications](guide:structure-applications).
  13. *
  14. * @property \yii\web\AssetManager $assetManager The asset manager application component. This property is
  15. * read-only.
  16. * @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
  17. * if auth manager is not configured. This property is read-only.
  18. * @property string $basePath The root directory of the application.
  19. * @property \yii\caching\CacheInterface $cache The cache application component. Null if the component is not
  20. * enabled. This property is read-only.
  21. * @property array $container Values given in terms of name-value pairs. This property is write-only.
  22. * @property \yii\db\Connection $db The database connection. This property is read-only.
  23. * @property \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application
  24. * component. This property is read-only.
  25. * @property \yii\i18n\Formatter $formatter The formatter application component. This property is read-only.
  26. * @property \yii\i18n\I18N $i18n The internationalization application component. This property is read-only.
  27. * @property \yii\log\Dispatcher $log The log dispatcher application component. This property is read-only.
  28. * @property \yii\mail\MailerInterface $mailer The mailer application component. This property is read-only.
  29. * @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only.
  30. * @property \yii\web\Response|\yii\console\Response $response The response component. This property is
  31. * read-only.
  32. * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
  33. * subdirectory under [[basePath]].
  34. * @property \yii\base\Security $security The security application component. This property is read-only.
  35. * @property string $timeZone The time zone used by this application.
  36. * @property string $uniqueId The unique ID of the module. This property is read-only.
  37. * @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
  38. * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
  39. * [[basePath]].
  40. * @property View|\yii\web\View $view The view application component that is used to render various view
  41. * files. This property is read-only.
  42. *
  43. * @author Qiang Xue <qiang.xue@gmail.com>
  44. * @since 2.0
  45. */
  46. abstract class Application extends Module
  47. {
  48. /**
  49. * @event Event an event raised before the application starts to handle a request.
  50. */
  51. const EVENT_BEFORE_REQUEST = 'beforeRequest';
  52. /**
  53. * @event Event an event raised after the application successfully handles a request (before the response is sent out).
  54. */
  55. const EVENT_AFTER_REQUEST = 'afterRequest';
  56. /**
  57. * Application state used by [[state]]: application just started.
  58. */
  59. const STATE_BEGIN = 0;
  60. /**
  61. * Application state used by [[state]]: application is initializing.
  62. */
  63. const STATE_INIT = 1;
  64. /**
  65. * Application state used by [[state]]: application is triggering [[EVENT_BEFORE_REQUEST]].
  66. */
  67. const STATE_BEFORE_REQUEST = 2;
  68. /**
  69. * Application state used by [[state]]: application is handling the request.
  70. */
  71. const STATE_HANDLING_REQUEST = 3;
  72. /**
  73. * Application state used by [[state]]: application is triggering [[EVENT_AFTER_REQUEST]]..
  74. */
  75. const STATE_AFTER_REQUEST = 4;
  76. /**
  77. * Application state used by [[state]]: application is about to send response.
  78. */
  79. const STATE_SENDING_RESPONSE = 5;
  80. /**
  81. * Application state used by [[state]]: application has ended.
  82. */
  83. const STATE_END = 6;
  84. /**
  85. * @var string the namespace that controller classes are located in.
  86. * This namespace will be used to load controller classes by prepending it to the controller class name.
  87. * The default namespace is `app\controllers`.
  88. *
  89. * Please refer to the [guide about class autoloading](guide:concept-autoloading.md) for more details.
  90. */
  91. public $controllerNamespace = 'app\\controllers';
  92. /**
  93. * @var string the application name.
  94. */
  95. public $name = 'My Application';
  96. /**
  97. * @var string the charset currently used for the application.
  98. */
  99. public $charset = 'UTF-8';
  100. /**
  101. * @var string the language that is meant to be used for end users. It is recommended that you
  102. * use [IETF language tags](http://en.wikipedia.org/wiki/IETF_language_tag). For example, `en` stands
  103. * for English, while `en-US` stands for English (United States).
  104. * @see sourceLanguage
  105. */
  106. public $language = 'en-US';
  107. /**
  108. * @var string the language that the application is written in. This mainly refers to
  109. * the language that the messages and view files are written in.
  110. * @see language
  111. */
  112. public $sourceLanguage = 'en-US';
  113. /**
  114. * @var Controller the currently active controller instance
  115. */
  116. public $controller;
  117. /**
  118. * @var string|bool the layout that should be applied for views in this application. Defaults to 'main'.
  119. * If this is false, layout will be disabled.
  120. */
  121. public $layout = 'main';
  122. /**
  123. * @var string the requested route
  124. */
  125. public $requestedRoute;
  126. /**
  127. * @var Action the requested Action. If null, it means the request cannot be resolved into an action.
  128. */
  129. public $requestedAction;
  130. /**
  131. * @var array the parameters supplied to the requested action.
  132. */
  133. public $requestedParams;
  134. /**
  135. * @var array list of installed Yii extensions. Each array element represents a single extension
  136. * with the following structure:
  137. *
  138. * ```php
  139. * [
  140. * 'name' => 'extension name',
  141. * 'version' => 'version number',
  142. * 'bootstrap' => 'BootstrapClassName', // optional, may also be a configuration array
  143. * 'alias' => [
  144. * '@alias1' => 'to/path1',
  145. * '@alias2' => 'to/path2',
  146. * ],
  147. * ]
  148. * ```
  149. *
  150. * The "bootstrap" class listed above will be instantiated during the application
  151. * [[bootstrap()|bootstrapping process]]. If the class implements [[BootstrapInterface]],
  152. * its [[BootstrapInterface::bootstrap()|bootstrap()]] method will be also be called.
  153. *
  154. * If not set explicitly in the application config, this property will be populated with the contents of
  155. * `@vendor/yiisoft/extensions.php`.
  156. */
  157. public $extensions;
  158. /**
  159. * @var array list of components that should be run during the application [[bootstrap()|bootstrapping process]].
  160. *
  161. * Each component may be specified in one of the following formats:
  162. *
  163. * - an application component ID as specified via [[components]].
  164. * - a module ID as specified via [[modules]].
  165. * - a class name.
  166. * - a configuration array.
  167. * - a Closure
  168. *
  169. * During the bootstrapping process, each component will be instantiated. If the component class
  170. * implements [[BootstrapInterface]], its [[BootstrapInterface::bootstrap()|bootstrap()]] method
  171. * will be also be called.
  172. */
  173. public $bootstrap = [];
  174. /**
  175. * @var int the current application state during a request handling life cycle.
  176. * This property is managed by the application. Do not modify this property.
  177. */
  178. public $state;
  179. /**
  180. * @var array list of loaded modules indexed by their class names.
  181. */
  182. public $loadedModules = [];
  183. /**
  184. * Constructor.
  185. * @param array $config name-value pairs that will be used to initialize the object properties.
  186. * Note that the configuration must contain both [[id]] and [[basePath]].
  187. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  188. */
  189. public function __construct($config = [])
  190. {
  191. Yii::$app = $this;
  192. static::setInstance($this);
  193. $this->state = self::STATE_BEGIN;
  194. $this->preInit($config);
  195. $this->registerErrorHandler($config);
  196. Component::__construct($config);
  197. }
  198. /**
  199. * Pre-initializes the application.
  200. * This method is called at the beginning of the application constructor.
  201. * It initializes several important application properties.
  202. * If you override this method, please make sure you call the parent implementation.
  203. * @param array $config the application configuration
  204. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  205. */
  206. public function preInit(&$config)
  207. {
  208. if (!isset($config['id'])) {
  209. throw new InvalidConfigException('The "id" configuration for the Application is required.');
  210. }
  211. if (isset($config['basePath'])) {
  212. $this->setBasePath($config['basePath']);
  213. unset($config['basePath']);
  214. } else {
  215. throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
  216. }
  217. if (isset($config['vendorPath'])) {
  218. $this->setVendorPath($config['vendorPath']);
  219. unset($config['vendorPath']);
  220. } else {
  221. // set "@vendor"
  222. $this->getVendorPath();
  223. }
  224. if (isset($config['runtimePath'])) {
  225. $this->setRuntimePath($config['runtimePath']);
  226. unset($config['runtimePath']);
  227. } else {
  228. // set "@runtime"
  229. $this->getRuntimePath();
  230. }
  231. if (isset($config['timeZone'])) {
  232. $this->setTimeZone($config['timeZone']);
  233. unset($config['timeZone']);
  234. } elseif (!ini_get('date.timezone')) {
  235. $this->setTimeZone('UTC');
  236. }
  237. if (isset($config['container'])) {
  238. $this->setContainer($config['container']);
  239. unset($config['container']);
  240. }
  241. // merge core components with custom components
  242. foreach ($this->coreComponents() as $id => $component) {
  243. if (!isset($config['components'][$id])) {
  244. $config['components'][$id] = $component;
  245. } elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
  246. $config['components'][$id]['class'] = $component['class'];
  247. }
  248. }
  249. }
  250. /**
  251. * {@inheritdoc}
  252. */
  253. public function init()
  254. {
  255. $this->state = self::STATE_INIT;
  256. $this->bootstrap();
  257. }
  258. /**
  259. * Initializes extensions and executes bootstrap components.
  260. * This method is called by [[init()]] after the application has been fully configured.
  261. * If you override this method, make sure you also call the parent implementation.
  262. */
  263. protected function bootstrap()
  264. {
  265. if ($this->extensions === null) {
  266. $file = Yii::getAlias('@vendor/yiisoft/extensions.php');
  267. $this->extensions = is_file($file) ? include $file : [];
  268. }
  269. foreach ($this->extensions as $extension) {
  270. if (!empty($extension['alias'])) {
  271. foreach ($extension['alias'] as $name => $path) {
  272. Yii::setAlias($name, $path);
  273. }
  274. }
  275. if (isset($extension['bootstrap'])) {
  276. $component = Yii::createObject($extension['bootstrap']);
  277. if ($component instanceof BootstrapInterface) {
  278. Yii::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
  279. $component->bootstrap($this);
  280. } else {
  281. Yii::debug('Bootstrap with ' . get_class($component), __METHOD__);
  282. }
  283. }
  284. }
  285. foreach ($this->bootstrap as $mixed) {
  286. $component = null;
  287. if ($mixed instanceof \Closure) {
  288. Yii::debug('Bootstrap with Closure', __METHOD__);
  289. if (!$component = call_user_func($mixed, $this)) {
  290. continue;
  291. }
  292. } elseif (is_string($mixed)) {
  293. if ($this->has($mixed)) {
  294. $component = $this->get($mixed);
  295. } elseif ($this->hasModule($mixed)) {
  296. $component = $this->getModule($mixed);
  297. } elseif (strpos($mixed, '\\') === false) {
  298. throw new InvalidConfigException("Unknown bootstrapping component ID: $mixed");
  299. }
  300. }
  301. if (!isset($component)) {
  302. $component = Yii::createObject($mixed);
  303. }
  304. if ($component instanceof BootstrapInterface) {
  305. Yii::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
  306. $component->bootstrap($this);
  307. } else {
  308. Yii::debug('Bootstrap with ' . get_class($component), __METHOD__);
  309. }
  310. }
  311. }
  312. /**
  313. * Registers the errorHandler component as a PHP error handler.
  314. * @param array $config application config
  315. */
  316. protected function registerErrorHandler(&$config)
  317. {
  318. if (YII_ENABLE_ERROR_HANDLER) {
  319. if (!isset($config['components']['errorHandler']['class'])) {
  320. echo "Error: no errorHandler component is configured.\n";
  321. exit(1);
  322. }
  323. $this->set('errorHandler', $config['components']['errorHandler']);
  324. unset($config['components']['errorHandler']);
  325. $this->getErrorHandler()->register();
  326. }
  327. }
  328. /**
  329. * Returns an ID that uniquely identifies this module among all modules within the current application.
  330. * Since this is an application instance, it will always return an empty string.
  331. * @return string the unique ID of the module.
  332. */
  333. public function getUniqueId()
  334. {
  335. return '';
  336. }
  337. /**
  338. * Sets the root directory of the application and the @app alias.
  339. * This method can only be invoked at the beginning of the constructor.
  340. * @param string $path the root directory of the application.
  341. * @property string the root directory of the application.
  342. * @throws InvalidArgumentException if the directory does not exist.
  343. */
  344. public function setBasePath($path)
  345. {
  346. parent::setBasePath($path);
  347. Yii::setAlias('@app', $this->getBasePath());
  348. }
  349. /**
  350. * Runs the application.
  351. * This is the main entrance of an application.
  352. * @return int the exit status (0 means normal, non-zero values mean abnormal)
  353. */
  354. public function run()
  355. {
  356. try {
  357. $this->state = self::STATE_BEFORE_REQUEST;
  358. $this->trigger(self::EVENT_BEFORE_REQUEST);
  359. $this->state = self::STATE_HANDLING_REQUEST;
  360. $response = $this->handleRequest($this->getRequest());
  361. $this->state = self::STATE_AFTER_REQUEST;
  362. $this->trigger(self::EVENT_AFTER_REQUEST);
  363. $this->state = self::STATE_SENDING_RESPONSE;
  364. $response->send();
  365. $this->state = self::STATE_END;
  366. return $response->exitStatus;
  367. } catch (ExitException $e) {
  368. $this->end($e->statusCode, isset($response) ? $response : null);
  369. return $e->statusCode;
  370. }
  371. }
  372. /**
  373. * Handles the specified request.
  374. *
  375. * This method should return an instance of [[Response]] or its child class
  376. * which represents the handling result of the request.
  377. *
  378. * @param Request $request the request to be handled
  379. * @return Response the resulting response
  380. */
  381. abstract public function handleRequest($request);
  382. private $_runtimePath;
  383. /**
  384. * Returns the directory that stores runtime files.
  385. * @return string the directory that stores runtime files.
  386. * Defaults to the "runtime" subdirectory under [[basePath]].
  387. */
  388. public function getRuntimePath()
  389. {
  390. if ($this->_runtimePath === null) {
  391. $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
  392. }
  393. return $this->_runtimePath;
  394. }
  395. /**
  396. * Sets the directory that stores runtime files.
  397. * @param string $path the directory that stores runtime files.
  398. */
  399. public function setRuntimePath($path)
  400. {
  401. $this->_runtimePath = Yii::getAlias($path);
  402. Yii::setAlias('@runtime', $this->_runtimePath);
  403. }
  404. private $_vendorPath;
  405. /**
  406. * Returns the directory that stores vendor files.
  407. * @return string the directory that stores vendor files.
  408. * Defaults to "vendor" directory under [[basePath]].
  409. */
  410. public function getVendorPath()
  411. {
  412. if ($this->_vendorPath === null) {
  413. $this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
  414. }
  415. return $this->_vendorPath;
  416. }
  417. /**
  418. * Sets the directory that stores vendor files.
  419. * @param string $path the directory that stores vendor files.
  420. */
  421. public function setVendorPath($path)
  422. {
  423. $this->_vendorPath = Yii::getAlias($path);
  424. Yii::setAlias('@vendor', $this->_vendorPath);
  425. Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower');
  426. Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');
  427. }
  428. /**
  429. * Returns the time zone used by this application.
  430. * This is a simple wrapper of PHP function date_default_timezone_get().
  431. * If time zone is not configured in php.ini or application config,
  432. * it will be set to UTC by default.
  433. * @return string the time zone used by this application.
  434. * @see https://secure.php.net/manual/en/function.date-default-timezone-get.php
  435. */
  436. public function getTimeZone()
  437. {
  438. return date_default_timezone_get();
  439. }
  440. /**
  441. * Sets the time zone used by this application.
  442. * This is a simple wrapper of PHP function date_default_timezone_set().
  443. * Refer to the [php manual](https://secure.php.net/manual/en/timezones.php) for available timezones.
  444. * @param string $value the time zone used by this application.
  445. * @see https://secure.php.net/manual/en/function.date-default-timezone-set.php
  446. */
  447. public function setTimeZone($value)
  448. {
  449. date_default_timezone_set($value);
  450. }
  451. /**
  452. * Returns the database connection component.
  453. * @return \yii\db\Connection the database connection.
  454. */
  455. public function getDb()
  456. {
  457. return $this->get('db');
  458. }
  459. /**
  460. * Returns the log dispatcher component.
  461. * @return \yii\log\Dispatcher the log dispatcher application component.
  462. */
  463. public function getLog()
  464. {
  465. return $this->get('log');
  466. }
  467. /**
  468. * Returns the error handler component.
  469. * @return \yii\web\ErrorHandler|\yii\console\ErrorHandler the error handler application component.
  470. */
  471. public function getErrorHandler()
  472. {
  473. return $this->get('errorHandler');
  474. }
  475. /**
  476. * Returns the cache component.
  477. * @return \yii\caching\CacheInterface the cache application component. Null if the component is not enabled.
  478. */
  479. public function getCache()
  480. {
  481. return $this->get('cache', false);
  482. }
  483. /**
  484. * Returns the formatter component.
  485. * @return \yii\i18n\Formatter the formatter application component.
  486. */
  487. public function getFormatter()
  488. {
  489. return $this->get('formatter');
  490. }
  491. /**
  492. * Returns the request component.
  493. * @return \yii\web\Request|\yii\console\Request the request component.
  494. */
  495. public function getRequest()
  496. {
  497. return $this->get('request');
  498. }
  499. /**
  500. * Returns the response component.
  501. * @return \yii\web\Response|\yii\console\Response the response component.
  502. */
  503. public function getResponse()
  504. {
  505. return $this->get('response');
  506. }
  507. /**
  508. * Returns the view object.
  509. * @return View|\yii\web\View the view application component that is used to render various view files.
  510. */
  511. public function getView()
  512. {
  513. return $this->get('view');
  514. }
  515. /**
  516. * Returns the URL manager for this application.
  517. * @return \yii\web\UrlManager the URL manager for this application.
  518. */
  519. public function getUrlManager()
  520. {
  521. return $this->get('urlManager');
  522. }
  523. /**
  524. * Returns the internationalization (i18n) component.
  525. * @return \yii\i18n\I18N the internationalization application component.
  526. */
  527. public function getI18n()
  528. {
  529. return $this->get('i18n');
  530. }
  531. /**
  532. * Returns the mailer component.
  533. * @return \yii\mail\MailerInterface the mailer application component.
  534. */
  535. public function getMailer()
  536. {
  537. return $this->get('mailer');
  538. }
  539. /**
  540. * Returns the auth manager for this application.
  541. * @return \yii\rbac\ManagerInterface the auth manager application component.
  542. * Null is returned if auth manager is not configured.
  543. */
  544. public function getAuthManager()
  545. {
  546. return $this->get('authManager', false);
  547. }
  548. /**
  549. * Returns the asset manager.
  550. * @return \yii\web\AssetManager the asset manager application component.
  551. */
  552. public function getAssetManager()
  553. {
  554. return $this->get('assetManager');
  555. }
  556. /**
  557. * Returns the security component.
  558. * @return \yii\base\Security the security application component.
  559. */
  560. public function getSecurity()
  561. {
  562. return $this->get('security');
  563. }
  564. /**
  565. * Returns the configuration of core application components.
  566. * @see set()
  567. */
  568. public function coreComponents()
  569. {
  570. return [
  571. 'log' => ['class' => 'yii\log\Dispatcher'],
  572. 'view' => ['class' => 'yii\web\View'],
  573. 'formatter' => ['class' => 'yii\i18n\Formatter'],
  574. 'i18n' => ['class' => 'yii\i18n\I18N'],
  575. 'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
  576. 'urlManager' => ['class' => 'yii\web\UrlManager'],
  577. 'assetManager' => ['class' => 'yii\web\AssetManager'],
  578. 'security' => ['class' => 'yii\base\Security'],
  579. ];
  580. }
  581. /**
  582. * Terminates the application.
  583. * This method replaces the `exit()` function by ensuring the application life cycle is completed
  584. * before terminating the application.
  585. * @param int $status the exit status (value 0 means normal exit while other values mean abnormal exit).
  586. * @param Response $response the response to be sent. If not set, the default application [[response]] component will be used.
  587. * @throws ExitException if the application is in testing mode
  588. */
  589. public function end($status = 0, $response = null)
  590. {
  591. if ($this->state === self::STATE_BEFORE_REQUEST || $this->state === self::STATE_HANDLING_REQUEST) {
  592. $this->state = self::STATE_AFTER_REQUEST;
  593. $this->trigger(self::EVENT_AFTER_REQUEST);
  594. }
  595. if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) {
  596. $this->state = self::STATE_END;
  597. $response = $response ?: $this->getResponse();
  598. $response->send();
  599. }
  600. if (YII_ENV_TEST) {
  601. throw new ExitException($status);
  602. }
  603. exit($status);
  604. }
  605. /**
  606. * Configures [[Yii::$container]] with the $config.
  607. *
  608. * @param array $config values given in terms of name-value pairs
  609. * @since 2.0.11
  610. */
  611. public function setContainer($config)
  612. {
  613. Yii::configure(Yii::$container, $config);
  614. }
  615. }