Application.php 22.6 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8 9
namespace yii\base;

Qiang Xue committed
10
use Yii;
.  
Qiang Xue committed
11

w  
Qiang Xue committed
12 13 14
/**
 * Application is the base class for all application classes.
 *
Carsten Brandt committed
15 16 17
 * @property \yii\web\AssetManager $assetManager The asset manager application component. This property is
 * read-only.
 * @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
18
 * if auth manager is not configured. This property is read-only.
19
 * @property string $basePath The root directory of the application.
20
 * @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled.
21 22
 * This property is read-only.
 * @property \yii\db\Connection $db The database connection. This property is read-only.
Carsten Brandt committed
23 24
 * @property \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application
 * component. This property is read-only.
25
 * @property \yii\i18n\Formatter $formatter The formatter application component. This property is read-only.
Carsten Brandt committed
26 27 28
 * @property \yii\i18n\I18N $i18n The internationalization application component. This property is read-only.
 * @property \yii\log\Dispatcher $log The log dispatcher application component. This property is read-only.
 * @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.
Carsten Brandt committed
30 31
 * @property \yii\web\Response|\yii\console\Response $response The response component. This property is
 * read-only.
32 33
 * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
 * subdirectory under [[basePath]].
Carsten Brandt committed
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 37 38 39
 * @property string $uniqueId The unique ID of the module. This property is read-only.
 * @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
 * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
 * [[basePath]].
Carsten Brandt committed
40 41
 * @property View|\yii\web\View $view The view application component that is used to render various view
 * files. This property is read-only.
42
 *
w  
Qiang Xue committed
43 44
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
45
 */
46
abstract class Application extends Module
w  
Qiang Xue committed
47
{
48 49 50 51 52 53 54 55
    /**
     * @event Event an event raised before the application starts to handle a request.
     */
    const EVENT_BEFORE_REQUEST = 'beforeRequest';
    /**
     * @event Event an event raised after the application successfully handles a request (before the response is sent out).
     */
    const EVENT_AFTER_REQUEST = 'afterRequest';
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    /**
     * Application state used by [[state]]: application just started.
     */
    const STATE_BEGIN = 0;
    /**
     * Application state used by [[state]]: application is initializing.
     */
    const STATE_INIT = 1;
    /**
     * Application state used by [[state]]: application is triggering [[EVENT_BEFORE_REQUEST]].
     */
    const STATE_BEFORE_REQUEST = 2;
    /**
     * Application state used by [[state]]: application is handling the request.
     */
    const STATE_HANDLING_REQUEST = 3;
    /**
     * Application state used by [[state]]: application is triggering [[EVENT_AFTER_REQUEST]]..
     */
    const STATE_AFTER_REQUEST = 4;
    /**
     * Application state used by [[state]]: application is about to send response.
     */
    const STATE_SENDING_RESPONSE = 5;
    /**
     * Application state used by [[state]]: application has ended.
     */
    const STATE_END = 6;

85
    /**
86
     * @var string the namespace that controller classes are located in.
87 88
     * This namespace will be used to load controller classes by prepending it to the controller class name.
     * The default namespace is `app\controllers`.
89
     *
90
     * Please refer to the [guide about class autoloading](guide:concept-autoloading.md) for more details.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
     */
    public $controllerNamespace = 'app\\controllers';
    /**
     * @var string the application name.
     */
    public $name = 'My Application';
    /**
     * @var string the version of this application.
     */
    public $version = '1.0';
    /**
     * @var string the charset currently used for the application.
     */
    public $charset = 'UTF-8';
    /**
Qiang Xue committed
106 107 108
     * @var string the language that is meant to be used for end users. It is recommended that you
     * use [IETF language tags](http://en.wikipedia.org/wiki/IETF_language_tag). For example, `en` stands
     * for English, while `en-US` stands for English (United States).
109 110
     * @see sourceLanguage
     */
111
    public $language = 'en-US';
112 113 114 115 116
    /**
     * @var string the language that the application is written in. This mainly refers to
     * the language that the messages and view files are written in.
     * @see language
     */
117
    public $sourceLanguage = 'en-US';
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    /**
     * @var Controller the currently active controller instance
     */
    public $controller;
    /**
     * @var string|boolean the layout that should be applied for views in this application. Defaults to 'main'.
     * If this is false, layout will be disabled.
     */
    public $layout = 'main';
    /**
     * @var string the requested route
     */
    public $requestedRoute;
    /**
     * @var Action the requested Action. If null, it means the request cannot be resolved into an action.
     */
    public $requestedAction;
    /**
     * @var array the parameters supplied to the requested action.
     */
    public $requestedParams;
    /**
     * @var array list of installed Yii extensions. Each array element represents a single extension
     * with the following structure:
     *
     * ~~~
     * [
     *     'name' => 'extension name',
     *     'version' => 'version number',
147
     *     'bootstrap' => 'BootstrapClassName',  // optional, may also be a configuration array
Qiang Xue committed
148 149 150 151
     *     'alias' => [
     *         '@alias1' => 'to/path1',
     *         '@alias2' => 'to/path2',
     *     ],
152 153
     * ]
     * ~~~
154 155 156 157
     *
     * The "bootstrap" class listed above will be instantiated during the application
     * [[bootstrap()|bootstrapping process]]. If the class implements [[BootstrapInterface]],
     * its [[BootstrapInterface::bootstrap()|bootstrap()]] method will be also be called.
158
     *
Qiang Xue committed
159
     * If not set explicitly in the application config, this property will be populated with the contents of
160
     * `@vendor/yiisoft/extensions.php`.
161
     */
162
    public $extensions;
163
    /**
164
     * @var array list of components that should be run during the application [[bootstrap()|bootstrapping process]].
165
     *
166
     * Each component may be specified in one of the following formats:
167 168 169 170 171 172
     *
     * - an application component ID as specified via [[components]].
     * - a module ID as specified via [[modules]].
     * - a class name.
     * - a configuration array.
     *
173 174 175
     * During the bootstrapping process, each component will be instantiated. If the component class
     * implements [[BootstrapInterface]], its [[BootstrapInterface::bootstrap()|bootstrap()]] method
     * will be also be called.
176 177
     */
    public $bootstrap = [];
178 179 180 181
    /**
     * @var integer the current application state during a request handling life cycle.
     * This property is managed by the application. Do not modify this property.
     */
Qiang Xue committed
182
    public $state;
183 184 185 186
    /**
     * @var array list of loaded modules indexed by their class names.
     */
    public $loadedModules = [];
187 188 189 190


    /**
     * Constructor.
191 192
     * @param array $config name-value pairs that will be used to initialize the object properties.
     * Note that the configuration must contain both [[id]] and [[basePath]].
193 194 195 196 197
     * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
     */
    public function __construct($config = [])
    {
        Yii::$app = $this;
198
        $this->setInstance($this);
199

200 201
        $this->state = self::STATE_BEGIN;

202 203
        $this->preInit($config);

204 205
        $this->registerErrorHandler($config);

206 207 208 209 210 211 212 213
        Component::__construct($config);
    }

    /**
     * Pre-initializes the application.
     * This method is called at the beginning of the application constructor.
     * It initializes several important application properties.
     * If you override this method, please make sure you call the parent implementation.
214
     * @param array $config the application configuration
215 216 217 218 219
     * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
     */
    public function preInit(&$config)
    {
        if (!isset($config['id'])) {
220
            throw new InvalidConfigException('The "id" configuration for the Application is required.');
221 222 223 224 225
        }
        if (isset($config['basePath'])) {
            $this->setBasePath($config['basePath']);
            unset($config['basePath']);
        } else {
226
            throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        }

        if (isset($config['vendorPath'])) {
            $this->setVendorPath($config['vendorPath']);
            unset($config['vendorPath']);
        } else {
            // set "@vendor"
            $this->getVendorPath();
        }
        if (isset($config['runtimePath'])) {
            $this->setRuntimePath($config['runtimePath']);
            unset($config['runtimePath']);
        } else {
            // set "@runtime"
            $this->getRuntimePath();
        }

        if (isset($config['timeZone'])) {
            $this->setTimeZone($config['timeZone']);
            unset($config['timeZone']);
        } elseif (!ini_get('date.timezone')) {
            $this->setTimeZone('UTC');
        }
250 251

        // merge core components with custom components
Qiang Xue committed
252 253 254 255 256
        foreach ($this->coreComponents() as $id => $component) {
            if (!isset($config['components'][$id])) {
                $config['components'][$id] = $component;
            } elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
                $config['components'][$id]['class'] = $component['class'];
257 258
            }
        }
259 260 261 262 263 264 265
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
266
        $this->state = self::STATE_INIT;
267
        $this->bootstrap();
268 269 270
    }

    /**
271 272 273
     * Initializes extensions and executes bootstrap components.
     * This method is called by [[init()]] after the application has been fully configured.
     * If you override this method, make sure you also call the parent implementation.
274
     */
275
    protected function bootstrap()
276
    {
277
        if ($this->extensions === null) {
278 279
            $file = Yii::getAlias('@vendor/yiisoft/extensions.php');
            $this->extensions = is_file($file) ? include($file) : [];
280
        }
281
        foreach ($this->extensions as $extension) {
282 283 284 285 286 287
            if (!empty($extension['alias'])) {
                foreach ($extension['alias'] as $name => $path) {
                    Yii::setAlias($name, $path);
                }
            }
            if (isset($extension['bootstrap'])) {
288 289
                $component = Yii::createObject($extension['bootstrap']);
                if ($component instanceof BootstrapInterface) {
290
                    Yii::trace("Bootstrap with " . get_class($component) . '::bootstrap()', __METHOD__);
291 292
                    $component->bootstrap($this);
                } else {
293
                    Yii::trace("Bootstrap with " . get_class($component), __METHOD__);
294
                }
295 296 297
            }
        }

298
        foreach ($this->bootstrap as $class) {
299
            $component = null;
300 301 302 303 304
            if (is_string($class)) {
                if ($this->has($class)) {
                    $component = $this->get($class);
                } elseif ($this->hasModule($class)) {
                    $component = $this->getModule($class);
305
                } elseif (strpos($class, '\\') === false) {
Qiang Xue committed
306
                    throw new InvalidConfigException("Unknown bootstrapping component ID: $class");
307 308 309 310 311 312 313
                }
            }
            if (!isset($component)) {
                $component = Yii::createObject($class);
            }

            if ($component instanceof BootstrapInterface) {
314
                Yii::trace("Bootstrap with " . get_class($component) . '::bootstrap()', __METHOD__);
315 316
                $component->bootstrap($this);
            } else {
317
                Yii::trace("Bootstrap with " . get_class($component), __METHOD__);
318 319
            }
        }
320 321
    }

322 323
    /**
     * Registers the errorHandler component as a PHP error handler.
324
     * @param array $config application config
325 326 327 328 329 330 331 332 333 334 335 336 337 338
     */
    protected function registerErrorHandler(&$config)
    {
        if (YII_ENABLE_ERROR_HANDLER) {
            if (!isset($config['components']['errorHandler']['class'])) {
                echo "Error: no errorHandler component is configured.\n";
                exit(1);
            }
            $this->set('errorHandler', $config['components']['errorHandler']);
            unset($config['components']['errorHandler']);
            $this->getErrorHandler()->register();
        }
    }

339 340 341 342 343 344 345 346 347 348 349 350 351
    /**
     * Returns an ID that uniquely identifies this module among all modules within the current application.
     * Since this is an application instance, it will always return an empty string.
     * @return string the unique ID of the module.
     */
    public function getUniqueId()
    {
        return '';
    }

    /**
     * Sets the root directory of the application and the @app alias.
     * This method can only be invoked at the beginning of the constructor.
352
     * @param string $path the root directory of the application.
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
     * @property string the root directory of the application.
     * @throws InvalidParamException if the directory does not exist.
     */
    public function setBasePath($path)
    {
        parent::setBasePath($path);
        Yii::setAlias('@app', $this->getBasePath());
    }

    /**
     * Runs the application.
     * This is the main entrance of an application.
     * @return integer the exit status (0 means normal, non-zero values mean abnormal)
     */
    public function run()
    {
369 370 371 372
        try {

            $this->state = self::STATE_BEFORE_REQUEST;
            $this->trigger(self::EVENT_BEFORE_REQUEST);
373

374 375
            $this->state = self::STATE_HANDLING_REQUEST;
            $response = $this->handleRequest($this->getRequest());
376

377 378
            $this->state = self::STATE_AFTER_REQUEST;
            $this->trigger(self::EVENT_AFTER_REQUEST);
379

380 381
            $this->state = self::STATE_SENDING_RESPONSE;
            $response->send();
382

383
            $this->state = self::STATE_END;
384

385 386 387 388 389 390 391 392
            return $response->exitStatus;

        } catch (ExitException $e) {

            $this->end($e->statusCode, isset($response) ? $response : null);
            return $e->statusCode;

        }
393 394 395 396 397 398 399 400
    }

    /**
     * Handles the specified request.
     *
     * This method should return an instance of [[Response]] or its child class
     * which represents the handling result of the request.
     *
401
     * @param Request $request the request to be handled
402 403 404 405 406 407 408 409 410
     * @return Response the resulting response
     */
    abstract public function handleRequest($request);

    private $_runtimePath;

    /**
     * Returns the directory that stores runtime files.
     * @return string the directory that stores runtime files.
411
     * Defaults to the "runtime" subdirectory under [[basePath]].
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
     */
    public function getRuntimePath()
    {
        if ($this->_runtimePath === null) {
            $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
        }

        return $this->_runtimePath;
    }

    /**
     * Sets the directory that stores runtime files.
     * @param string $path the directory that stores runtime files.
     */
    public function setRuntimePath($path)
    {
        $this->_runtimePath = Yii::getAlias($path);
        Yii::setAlias('@runtime', $this->_runtimePath);
    }

    private $_vendorPath;

    /**
     * Returns the directory that stores vendor files.
     * @return string the directory that stores vendor files.
437
     * Defaults to "vendor" directory under [[basePath]].
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
     */
    public function getVendorPath()
    {
        if ($this->_vendorPath === null) {
            $this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
        }

        return $this->_vendorPath;
    }

    /**
     * Sets the directory that stores vendor files.
     * @param string $path the directory that stores vendor files.
     */
    public function setVendorPath($path)
    {
        $this->_vendorPath = Yii::getAlias($path);
        Yii::setAlias('@vendor', $this->_vendorPath);
456 457
        Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower');
        Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    }

    /**
     * Returns the time zone used by this application.
     * This is a simple wrapper of PHP function date_default_timezone_get().
     * If time zone is not configured in php.ini or application config,
     * it will be set to UTC by default.
     * @return string the time zone used by this application.
     * @see http://php.net/manual/en/function.date-default-timezone-get.php
     */
    public function getTimeZone()
    {
        return date_default_timezone_get();
    }

    /**
     * Sets the time zone used by this application.
     * This is a simple wrapper of PHP function date_default_timezone_set().
     * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
     * @param string $value the time zone used by this application.
     * @see http://php.net/manual/en/function.date-default-timezone-set.php
     */
    public function setTimeZone($value)
    {
        date_default_timezone_set($value);
    }

    /**
     * Returns the database connection component.
Carsten Brandt committed
487
     * @return \yii\db\Connection the database connection.
488 489 490
     */
    public function getDb()
    {
491
        return $this->get('db');
492 493 494
    }

    /**
495
     * Returns the log dispatcher component.
Carsten Brandt committed
496
     * @return \yii\log\Dispatcher the log dispatcher application component.
497 498 499
     */
    public function getLog()
    {
500
        return $this->get('log');
501 502 503 504
    }

    /**
     * Returns the error handler component.
505
     * @return \yii\web\ErrorHandler|\yii\console\ErrorHandler the error handler application component.
506 507 508
     */
    public function getErrorHandler()
    {
509
        return $this->get('errorHandler');
510 511 512 513 514 515 516 517
    }

    /**
     * Returns the cache component.
     * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
     */
    public function getCache()
    {
518
        return $this->get('cache', false);
519 520 521 522
    }

    /**
     * Returns the formatter component.
523
     * @return \yii\i18n\Formatter the formatter application component.
524 525 526
     */
    public function getFormatter()
    {
527
        return $this->get('formatter');
528 529 530 531
    }

    /**
     * Returns the request component.
Carsten Brandt committed
532
     * @return \yii\web\Request|\yii\console\Request the request component.
533 534 535
     */
    public function getRequest()
    {
536
        return $this->get('request');
537 538
    }

539 540
    /**
     * Returns the response component.
Carsten Brandt committed
541
     * @return \yii\web\Response|\yii\console\Response the response component.
542 543 544 545 546 547
     */
    public function getResponse()
    {
        return $this->get('response');
    }

548 549
    /**
     * Returns the view object.
Carsten Brandt committed
550
     * @return View|\yii\web\View the view application component that is used to render various view files.
551 552 553
     */
    public function getView()
    {
554
        return $this->get('view');
555 556 557 558 559 560 561 562
    }

    /**
     * Returns the URL manager for this application.
     * @return \yii\web\UrlManager the URL manager for this application.
     */
    public function getUrlManager()
    {
563
        return $this->get('urlManager');
564 565 566 567
    }

    /**
     * Returns the internationalization (i18n) component
Carsten Brandt committed
568
     * @return \yii\i18n\I18N the internationalization application component.
569 570 571
     */
    public function getI18n()
    {
572
        return $this->get('i18n');
573 574 575 576
    }

    /**
     * Returns the mailer component.
Carsten Brandt committed
577
     * @return \yii\mail\MailerInterface the mailer application component.
578
     */
579
    public function getMailer()
580
    {
581
        return $this->get('mailer');
582 583 584 585
    }

    /**
     * Returns the auth manager for this application.
Carsten Brandt committed
586
     * @return \yii\rbac\ManagerInterface the auth manager application component.
587
     * Null is returned if auth manager is not configured.
588 589 590
     */
    public function getAuthManager()
    {
591
        return $this->get('authManager', false);
592 593
    }

594 595
    /**
     * Returns the asset manager.
Carsten Brandt committed
596
     * @return \yii\web\AssetManager the asset manager application component.
597 598 599 600 601 602
     */
    public function getAssetManager()
    {
        return $this->get('assetManager');
    }

603 604
    /**
     * Returns the security component.
Carsten Brandt committed
605
     * @return \yii\base\Security the security application component.
606 607 608 609 610 611
     */
    public function getSecurity()
    {
        return $this->get('security');
    }

612
    /**
Carsten Brandt committed
613 614
     * Returns the configuration of core application components.
     * @see set()
615
     */
616
    public function coreComponents()
617
    {
618
        return [
619
            'log' => ['class' => 'yii\log\Dispatcher'],
620
            'view' => ['class' => 'yii\web\View'],
621
            'formatter' => ['class' => 'yii\i18n\Formatter'],
622
            'i18n' => ['class' => 'yii\i18n\I18N'],
623
            'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
624
            'urlManager' => ['class' => 'yii\web\UrlManager'],
625
            'assetManager' => ['class' => 'yii\web\AssetManager'],
626
            'security' => ['class' => 'yii\base\Security'],
627
        ];
628 629
    }

630
    /**
Qiang Xue committed
631 632
     * Terminates the application.
     * This method replaces the `exit()` function by ensuring the application life cycle is completed
633
     * before terminating the application.
Qiang Xue committed
634
     * @param integer $status the exit status (value 0 means normal exit while other values mean abnormal exit).
635 636
     * @param Response $response the response to be sent. If not set, the default application [[response]] component will be used.
     * @throws ExitException if the application is in testing mode
Qiang Xue committed
637
     */
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
    public function end($status = 0, $response = null)
    {
        if ($this->state === self::STATE_BEFORE_REQUEST || $this->state === self::STATE_HANDLING_REQUEST) {
            $this->state = self::STATE_AFTER_REQUEST;
            $this->trigger(self::EVENT_AFTER_REQUEST);
        }

        if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) {
            $this->state = self::STATE_END;
            $response = $response ? : $this->getResponse();
            $response->send();
        }

        if (YII_ENV_TEST) {
            throw new ExitException($status);
        } else {
            exit($status);
        }
    }
w  
Qiang Xue committed
657
}