Application.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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\Cache $cache The cache application component. Null if the component is not enabled.
  20. * 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. *
  168. * During the bootstrapping process, each component will be instantiated. If the component class
  169. * implements [[BootstrapInterface]], its [[BootstrapInterface::bootstrap()|bootstrap()]] method
  170. * will be also be called.
  171. */
  172. public $bootstrap = [];
  173. /**
  174. * @var int the current application state during a request handling life cycle.
  175. * This property is managed by the application. Do not modify this property.
  176. */
  177. public $state;
  178. /**
  179. * @var array list of loaded modules indexed by their class names.
  180. */
  181. public $loadedModules = [];
  182. /**
  183. * Constructor.
  184. * @param array $config name-value pairs that will be used to initialize the object properties.
  185. * Note that the configuration must contain both [[id]] and [[basePath]].
  186. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  187. */
  188. public function __construct($config = [])
  189. {
  190. Yii::$app = $this;
  191. static::setInstance($this);
  192. $this->state = self::STATE_BEGIN;
  193. $this->preInit($config);
  194. $this->registerErrorHandler($config);
  195. Component::__construct($config);
  196. }
  197. /**
  198. * Pre-initializes the application.
  199. * This method is called at the beginning of the application constructor.
  200. * It initializes several important application properties.
  201. * If you override this method, please make sure you call the parent implementation.
  202. * @param array $config the application configuration
  203. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
  204. */
  205. public function preInit(&$config)
  206. {
  207. if (!isset($config['id'])) {
  208. throw new InvalidConfigException('The "id" configuration for the Application is required.');
  209. }
  210. if (isset($config['basePath'])) {
  211. $this->setBasePath($config['basePath']);
  212. unset($config['basePath']);
  213. } else {
  214. throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
  215. }
  216. if (isset($config['vendorPath'])) {
  217. $this->setVendorPath($config['vendorPath']);
  218. unset($config['vendorPath']);
  219. } else {
  220. // set "@vendor"
  221. $this->getVendorPath();
  222. }
  223. if (isset($config['runtimePath'])) {
  224. $this->setRuntimePath($config['runtimePath']);
  225. unset($config['runtimePath']);
  226. } else {
  227. // set "@runtime"
  228. $this->getRuntimePath();
  229. }
  230. if (isset($config['timeZone'])) {
  231. $this->setTimeZone($config['timeZone']);
  232. unset($config['timeZone']);
  233. } elseif (!ini_get('date.timezone')) {
  234. $this->setTimeZone('UTC');
  235. }
  236. if (isset($config['container'])) {
  237. $this->setContainer($config['container']);
  238. unset($config['container']);
  239. }
  240. // merge core components with custom components
  241. foreach ($this->coreComponents() as $id => $component) {
  242. if (!isset($config['components'][$id])) {
  243. $config['components'][$id] = $component;
  244. } elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
  245. $config['components'][$id]['class'] = $component['class'];
  246. }
  247. }
  248. }
  249. /**
  250. * @inheritdoc
  251. */
  252. public function init()
  253. {
  254. $this->state = self::STATE_INIT;
  255. $this->bootstrap();
  256. }
  257. /**
  258. * Initializes extensions and executes bootstrap components.
  259. * This method is called by [[init()]] after the application has been fully configured.
  260. * If you override this method, make sure you also call the parent implementation.
  261. */
  262. protected function bootstrap()
  263. {
  264. if ($this->extensions === null) {
  265. $file = Yii::getAlias('@vendor/yiisoft/extensions.php');
  266. $this->extensions = is_file($file) ? include($file) : [];
  267. }
  268. foreach ($this->extensions as $extension) {
  269. if (!empty($extension['alias'])) {
  270. foreach ($extension['alias'] as $name => $path) {
  271. Yii::setAlias($name, $path);
  272. }
  273. }
  274. if (isset($extension['bootstrap'])) {
  275. $component = Yii::createObject($extension['bootstrap']);
  276. if ($component instanceof BootstrapInterface) {
  277. Yii::trace('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
  278. $component->bootstrap($this);
  279. } else {
  280. Yii::trace('Bootstrap with ' . get_class($component), __METHOD__);
  281. }
  282. }
  283. }
  284. foreach ($this->bootstrap as $class) {
  285. $component = null;
  286. if (is_string($class)) {
  287. if ($this->has($class)) {
  288. $component = $this->get($class);
  289. } elseif ($this->hasModule($class)) {
  290. $component = $this->getModule($class);
  291. } elseif (strpos($class, '\\') === false) {
  292. throw new InvalidConfigException("Unknown bootstrapping component ID: $class");
  293. }
  294. }
  295. if (!isset($component)) {
  296. $component = Yii::createObject($class);
  297. }
  298. if ($component instanceof BootstrapInterface) {
  299. Yii::trace('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
  300. $component->bootstrap($this);
  301. } else {
  302. Yii::trace('Bootstrap with ' . get_class($component), __METHOD__);
  303. }
  304. }
  305. }
  306. /**
  307. * Registers the errorHandler component as a PHP error handler.
  308. * @param array $config application config
  309. */
  310. protected function registerErrorHandler(&$config)
  311. {
  312. if (YII_ENABLE_ERROR_HANDLER) {
  313. if (!isset($config['components']['errorHandler']['class'])) {
  314. echo "Error: no errorHandler component is configured.\n";
  315. exit(1);
  316. }
  317. $this->set('errorHandler', $config['components']['errorHandler']);
  318. unset($config['components']['errorHandler']);
  319. $this->getErrorHandler()->register();
  320. }
  321. }
  322. /**
  323. * Returns an ID that uniquely identifies this module among all modules within the current application.
  324. * Since this is an application instance, it will always return an empty string.
  325. * @return string the unique ID of the module.
  326. */
  327. public function getUniqueId()
  328. {
  329. return '';
  330. }
  331. /**
  332. * Sets the root directory of the application and the @app alias.
  333. * This method can only be invoked at the beginning of the constructor.
  334. * @param string $path the root directory of the application.
  335. * @property string the root directory of the application.
  336. * @throws InvalidParamException if the directory does not exist.
  337. */
  338. public function setBasePath($path)
  339. {
  340. parent::setBasePath($path);
  341. Yii::setAlias('@app', $this->getBasePath());
  342. }
  343. /**
  344. * Runs the application.
  345. * This is the main entrance of an application.
  346. * @return int the exit status (0 means normal, non-zero values mean abnormal)
  347. */
  348. public function run()
  349. {
  350. try {
  351. $this->state = self::STATE_BEFORE_REQUEST;
  352. $this->trigger(self::EVENT_BEFORE_REQUEST);
  353. $this->state = self::STATE_HANDLING_REQUEST;
  354. $response = $this->handleRequest($this->getRequest());
  355. $this->state = self::STATE_AFTER_REQUEST;
  356. $this->trigger(self::EVENT_AFTER_REQUEST);
  357. $this->state = self::STATE_SENDING_RESPONSE;
  358. $response->send();
  359. $this->state = self::STATE_END;
  360. return $response->exitStatus;
  361. } catch (ExitException $e) {
  362. $this->end($e->statusCode, isset($response) ? $response : null);
  363. return $e->statusCode;
  364. }
  365. }
  366. /**
  367. * Handles the specified request.
  368. *
  369. * This method should return an instance of [[Response]] or its child class
  370. * which represents the handling result of the request.
  371. *
  372. * @param Request $request the request to be handled
  373. * @return Response the resulting response
  374. */
  375. abstract public function handleRequest($request);
  376. private $_runtimePath;
  377. /**
  378. * Returns the directory that stores runtime files.
  379. * @return string the directory that stores runtime files.
  380. * Defaults to the "runtime" subdirectory under [[basePath]].
  381. */
  382. public function getRuntimePath()
  383. {
  384. if ($this->_runtimePath === null) {
  385. $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
  386. }
  387. return $this->_runtimePath;
  388. }
  389. /**
  390. * Sets the directory that stores runtime files.
  391. * @param string $path the directory that stores runtime files.
  392. */
  393. public function setRuntimePath($path)
  394. {
  395. $this->_runtimePath = Yii::getAlias($path);
  396. Yii::setAlias('@runtime', $this->_runtimePath);
  397. }
  398. private $_vendorPath;
  399. /**
  400. * Returns the directory that stores vendor files.
  401. * @return string the directory that stores vendor files.
  402. * Defaults to "vendor" directory under [[basePath]].
  403. */
  404. public function getVendorPath()
  405. {
  406. if ($this->_vendorPath === null) {
  407. $this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
  408. }
  409. return $this->_vendorPath;
  410. }
  411. /**
  412. * Sets the directory that stores vendor files.
  413. * @param string $path the directory that stores vendor files.
  414. */
  415. public function setVendorPath($path)
  416. {
  417. $this->_vendorPath = Yii::getAlias($path);
  418. Yii::setAlias('@vendor', $this->_vendorPath);
  419. Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower');
  420. Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');
  421. }
  422. /**
  423. * Returns the time zone used by this application.
  424. * This is a simple wrapper of PHP function date_default_timezone_get().
  425. * If time zone is not configured in php.ini or application config,
  426. * it will be set to UTC by default.
  427. * @return string the time zone used by this application.
  428. * @see http://php.net/manual/en/function.date-default-timezone-get.php
  429. */
  430. public function getTimeZone()
  431. {
  432. return date_default_timezone_get();
  433. }
  434. /**
  435. * Sets the time zone used by this application.
  436. * This is a simple wrapper of PHP function date_default_timezone_set().
  437. * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
  438. * @param string $value the time zone used by this application.
  439. * @see http://php.net/manual/en/function.date-default-timezone-set.php
  440. */
  441. public function setTimeZone($value)
  442. {
  443. date_default_timezone_set($value);
  444. }
  445. /**
  446. * Returns the database connection component.
  447. * @return \yii\db\Connection the database connection.
  448. */
  449. public function getDb()
  450. {
  451. return $this->get('db');
  452. }
  453. /**
  454. * Returns the log dispatcher component.
  455. * @return \yii\log\Dispatcher the log dispatcher application component.
  456. */
  457. public function getLog()
  458. {
  459. return $this->get('log');
  460. }
  461. /**
  462. * Returns the error handler component.
  463. * @return \yii\web\ErrorHandler|\yii\console\ErrorHandler the error handler application component.
  464. */
  465. public function getErrorHandler()
  466. {
  467. return $this->get('errorHandler');
  468. }
  469. /**
  470. * Returns the cache component.
  471. * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
  472. */
  473. public function getCache()
  474. {
  475. return $this->get('cache', false);
  476. }
  477. /**
  478. * Returns the formatter component.
  479. * @return \yii\i18n\Formatter the formatter application component.
  480. */
  481. public function getFormatter()
  482. {
  483. return $this->get('formatter');
  484. }
  485. /**
  486. * Returns the request component.
  487. * @return \yii\web\Request|\yii\console\Request the request component.
  488. */
  489. public function getRequest()
  490. {
  491. return $this->get('request');
  492. }
  493. /**
  494. * Returns the response component.
  495. * @return \yii\web\Response|\yii\console\Response the response component.
  496. */
  497. public function getResponse()
  498. {
  499. return $this->get('response');
  500. }
  501. /**
  502. * Returns the view object.
  503. * @return View|\yii\web\View the view application component that is used to render various view files.
  504. */
  505. public function getView()
  506. {
  507. return $this->get('view');
  508. }
  509. /**
  510. * Returns the URL manager for this application.
  511. * @return \yii\web\UrlManager the URL manager for this application.
  512. */
  513. public function getUrlManager()
  514. {
  515. return $this->get('urlManager');
  516. }
  517. /**
  518. * Returns the internationalization (i18n) component
  519. * @return \yii\i18n\I18N the internationalization application component.
  520. */
  521. public function getI18n()
  522. {
  523. return $this->get('i18n');
  524. }
  525. /**
  526. * Returns the mailer component.
  527. * @return \yii\mail\MailerInterface the mailer application component.
  528. */
  529. public function getMailer()
  530. {
  531. return $this->get('mailer');
  532. }
  533. /**
  534. * Returns the auth manager for this application.
  535. * @return \yii\rbac\ManagerInterface the auth manager application component.
  536. * Null is returned if auth manager is not configured.
  537. */
  538. public function getAuthManager()
  539. {
  540. return $this->get('authManager', false);
  541. }
  542. /**
  543. * Returns the asset manager.
  544. * @return \yii\web\AssetManager the asset manager application component.
  545. */
  546. public function getAssetManager()
  547. {
  548. return $this->get('assetManager');
  549. }
  550. /**
  551. * Returns the security component.
  552. * @return \yii\base\Security the security application component.
  553. */
  554. public function getSecurity()
  555. {
  556. return $this->get('security');
  557. }
  558. /**
  559. * Returns the configuration of core application components.
  560. * @see set()
  561. */
  562. public function coreComponents()
  563. {
  564. return [
  565. 'log' => ['class' => 'yii\log\Dispatcher'],
  566. 'view' => ['class' => 'yii\web\View'],
  567. 'formatter' => ['class' => 'yii\i18n\Formatter'],
  568. 'i18n' => ['class' => 'yii\i18n\I18N'],
  569. 'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
  570. 'urlManager' => ['class' => 'yii\web\UrlManager'],
  571. 'assetManager' => ['class' => 'yii\web\AssetManager'],
  572. 'security' => ['class' => 'yii\base\Security'],
  573. ];
  574. }
  575. /**
  576. * Terminates the application.
  577. * This method replaces the `exit()` function by ensuring the application life cycle is completed
  578. * before terminating the application.
  579. * @param int $status the exit status (value 0 means normal exit while other values mean abnormal exit).
  580. * @param Response $response the response to be sent. If not set, the default application [[response]] component will be used.
  581. * @throws ExitException if the application is in testing mode
  582. */
  583. public function end($status = 0, $response = null)
  584. {
  585. if ($this->state === self::STATE_BEFORE_REQUEST || $this->state === self::STATE_HANDLING_REQUEST) {
  586. $this->state = self::STATE_AFTER_REQUEST;
  587. $this->trigger(self::EVENT_AFTER_REQUEST);
  588. }
  589. if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) {
  590. $this->state = self::STATE_END;
  591. $response = $response ? : $this->getResponse();
  592. $response->send();
  593. }
  594. if (YII_ENV_TEST) {
  595. throw new ExitException($status);
  596. } else {
  597. exit($status);
  598. }
  599. }
  600. /**
  601. * Configures [[Yii::$container]] with the $config
  602. *
  603. * @param array $config values given in terms of name-value pairs
  604. * @since 2.0.11
  605. */
  606. public function setContainer($config)
  607. {
  608. Yii::configure(Yii::$container, $config);
  609. }
  610. }