Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

658 lines
23KB

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