Application.php 19.7 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
use yii\helpers\Console;
Qiang Xue committed
12
use yii\web\HttpException;
.  
Qiang Xue committed
13

w  
Qiang Xue committed
14 15 16
/**
 * Application is the base class for all application classes.
 *
17 18
 * @property \yii\rbac\Manager $authManager The auth manager for this application. Null is returned 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 23 24
 * This property is read-only.
 * @property \yii\db\Connection $db The database connection. This property is read-only.
 * @property ErrorHandler $errorHandler The error handler application component. This property is read-only.
 * @property \yii\base\Formatter $formatter The formatter application component. This property is read-only.
25
 * @property \yii\i18n\I18N $i18n The internationalization component. This property is read-only.
26
 * @property \yii\log\Dispatcher $log The log dispatcher component. This property is read-only.
Qiang Xue committed
27
 * @property \yii\mail\MailerInterface $mail The mailer interface. This property is read-only.
28 29 30
 * @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only.
 * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
 * subdirectory under [[basePath]].
31
 * @property string $timeZone The time zone used by this application.
32 33 34 35
 * @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]].
Qiang Xue committed
36 37
 * @property View|\yii\web\View $view The view object that is used to render various view files. This property
 * is read-only.
38
 *
w  
Qiang Xue committed
39 40
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
41
 */
42
abstract class Application extends Module
w  
Qiang Xue committed
43
{
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    /**
     * @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';
    /**
     * @event ActionEvent an event raised before executing a controller action.
     * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
     */
    const EVENT_BEFORE_ACTION = 'beforeAction';
    /**
     * @event ActionEvent an event raised after executing a controller action.
     */
    const EVENT_AFTER_ACTION = 'afterAction';

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    /**
     * 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;

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 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 147 148
    /**
     * @var string the namespace that controller classes are in. If not set,
     * it will use the "app\controllers" namespace.
     */
    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';
    /**
     * @var string the language that is meant to be used for end users.
     * @see sourceLanguage
     */
    public $language = 'en';
    /**
     * @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
     */
    public $sourceLanguage = 'en';
    /**
     * @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',
     *     'bootstrap' => 'BootstrapClassName',
Qiang Xue committed
149 150 151 152
     *     'alias' => [
     *         '@alias1' => 'to/path1',
     *         '@alias2' => 'to/path2',
     *     ],
153 154 155 156
     * ]
     * ~~~
     */
    public $extensions = [];
157
    /**
158 159 160
     * @var array list of bootstrap classes or their configurations. A bootstrap class must implement
     * [[BootstrapInterface]]. The [[BootstrapInterface::bootstrap()]] method of each bootstrap class
     * will be invoked at the beginning of [[init()]].
161 162
     */
    public $bootstrap = [];
163 164 165 166
    /**
     * @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
167
    public $state;
168 169 170 171


    /**
     * Constructor.
172 173
     * @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]].
174 175 176 177 178 179
     * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
     */
    public function __construct($config = [])
    {
        Yii::$app = $this;

180 181
        $this->state = self::STATE_BEGIN;

182
        $this->registerErrorHandler($config);
183 184 185 186 187 188 189 190 191 192
        $this->preInit($config);

        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.
193
     * @param array $config the application configuration
194 195 196 197 198
     * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
     */
    public function preInit(&$config)
    {
        if (!isset($config['id'])) {
199
            throw new InvalidConfigException('The "id" configuration for the Application is required.');
200 201 202 203 204
        }
        if (isset($config['basePath'])) {
            $this->setBasePath($config['basePath']);
            unset($config['basePath']);
        } else {
205
            throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        }

        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');
        }
229 230

        // merge core components with custom components
Qiang Xue committed
231 232 233 234 235
        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'];
236 237
            }
        }
238 239 240 241 242 243 244
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
245 246
        $this->state = self::STATE_INIT;

247
        $this->initExtensions($this->extensions);
248
        foreach ($this->bootstrap as $class) {
249 250 251
            /** @var BootstrapInterface $bootstrap */
            $bootstrap = Yii::createObject($class);
            $bootstrap->bootstrap($this);
252
        }
253 254 255 256 257 258
        parent::init();
    }

    /**
     * Initializes the extensions.
     * @param array $extensions the extensions to be initialized. Please refer to [[extensions]]
259
     * for the structure of the extension array.
260 261 262 263 264 265 266 267 268 269
     */
    protected function initExtensions($extensions)
    {
        foreach ($extensions as $extension) {
            if (!empty($extension['alias'])) {
                foreach ($extension['alias'] as $name => $path) {
                    Yii::setAlias($name, $path);
                }
            }
            if (isset($extension['bootstrap'])) {
270 271 272
                /** @var BootstrapInterface $bootstrap */
                $bootstrap = Yii::createObject($extension['bootstrap']);
                $bootstrap->bootstrap($this);
273 274 275 276 277 278 279 280 281 282
            }
        }
    }

    /**
     * Loads components that are declared in [[preload]].
     * @throws InvalidConfigException if a component or module to be preloaded is unknown
     */
    public function preloadComponents()
    {
283
        $this->get('log');
284 285 286
        parent::preloadComponents();
    }

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    /**
     * Registers the errorHandler component as a PHP error handler.
     */
    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();
        }
    }

303 304 305 306 307 308 309 310 311 312 313 314 315
    /**
     * 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.
316
     * @param string $path the root directory of the application.
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
     * @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()
    {
333 334 335 336
        try {

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

338 339
            $this->state = self::STATE_HANDLING_REQUEST;
            $response = $this->handleRequest($this->getRequest());
340

341 342
            $this->state = self::STATE_AFTER_REQUEST;
            $this->trigger(self::EVENT_AFTER_REQUEST);
343

344 345
            $this->state = self::STATE_SENDING_RESPONSE;
            $response->send();
346

347
            $this->state = self::STATE_END;
348

349 350 351 352 353 354 355 356
            return $response->exitStatus;

        } catch (ExitException $e) {

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

        }
357 358 359 360 361 362 363 364
    }

    /**
     * Handles the specified request.
     *
     * This method should return an instance of [[Response]] or its child class
     * which represents the handling result of the request.
     *
365
     * @param Request $request the request to be handled
366 367 368 369 370 371 372 373 374
     * @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.
375
     * Defaults to the "runtime" subdirectory under [[basePath]].
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
     */
    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.
401
     * Defaults to "vendor" directory under [[basePath]].
402 403 404 405 406 407 408 409 410 411 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 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
     */
    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);
    }

    /**
     * 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.
     * @return \yii\db\Connection the database connection
     */
    public function getDb()
    {
453
        return $this->get('db');
454 455 456
    }

    /**
457 458
     * Returns the log dispatcher component.
     * @return \yii\log\Dispatcher the log dispatcher component
459 460 461
     */
    public function getLog()
    {
462
        return $this->get('log');
463 464 465 466
    }

    /**
     * Returns the error handler component.
467
     * @return \yii\web\ErrorHandler|\yii\console\ErrorHandler the error handler application component.
468 469 470
     */
    public function getErrorHandler()
    {
471
        return $this->get('errorHandler');
472 473 474 475 476 477 478 479
    }

    /**
     * Returns the cache component.
     * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
     */
    public function getCache()
    {
480
        return $this->get('cache', false);
481 482 483 484 485 486 487 488
    }

    /**
     * Returns the formatter component.
     * @return \yii\base\Formatter the formatter application component.
     */
    public function getFormatter()
    {
489
        return $this->get('formatter');
490 491 492 493 494 495 496 497
    }

    /**
     * Returns the request component.
     * @return \yii\web\Request|\yii\console\Request the request component
     */
    public function getRequest()
    {
498
        return $this->get('request');
499 500
    }

501 502 503 504 505 506 507 508 509
    /**
     * Returns the response component.
     * @return \yii\web\Response|\yii\console\Response the response component
     */
    public function getResponse()
    {
        return $this->get('response');
    }

510 511 512 513 514 515
    /**
     * Returns the view object.
     * @return View|\yii\web\View the view object that is used to render various view files.
     */
    public function getView()
    {
516
        return $this->get('view');
517 518 519 520 521 522 523 524
    }

    /**
     * Returns the URL manager for this application.
     * @return \yii\web\UrlManager the URL manager for this application.
     */
    public function getUrlManager()
    {
525
        return $this->get('urlManager');
526 527 528 529 530 531 532 533
    }

    /**
     * Returns the internationalization (i18n) component
     * @return \yii\i18n\I18N the internationalization component
     */
    public function getI18n()
    {
534
        return $this->get('i18n');
535 536 537 538 539 540 541 542
    }

    /**
     * Returns the mailer component.
     * @return \yii\mail\MailerInterface the mailer interface
     */
    public function getMail()
    {
543
        return $this->get('mail');
544 545 546 547 548
    }

    /**
     * Returns the auth manager for this application.
     * @return \yii\rbac\Manager the auth manager for this application.
549
     * Null is returned if auth manager is not configured.
550 551 552
     */
    public function getAuthManager()
    {
553
        return $this->get('authManager', false);
554 555
    }

556 557 558 559 560 561 562 563 564
    /**
     * Returns the asset manager.
     * @return \yii\web\AssetManager the asset manager component
     */
    public function getAssetManager()
    {
        return $this->get('assetManager');
    }

565
    /**
566 567
     * Returns the core application components.
     * @see set
568
     */
569
    public function coreComponents()
570
    {
571
        return [
572
            'log' => ['class' => 'yii\log\Dispatcher'],
573
            'view' => ['class' => 'yii\web\View'],
574 575 576 577
            'formatter' => ['class' => 'yii\base\Formatter'],
            'i18n' => ['class' => 'yii\i18n\I18N'],
            'mail' => ['class' => 'yii\swiftmailer\Mailer'],
            'urlManager' => ['class' => 'yii\web\UrlManager'],
578
            'assetManager' => ['class' => 'yii\web\AssetManager'],
579
        ];
580 581
    }

582
    /**
Qiang Xue committed
583 584
     * Terminates the application.
     * This method replaces the `exit()` function by ensuring the application life cycle is completed
585
     * before terminating the application.
Qiang Xue committed
586
     * @param integer $status the exit status (value 0 means normal exit while other values mean abnormal exit).
587 588
     * @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
589
     */
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    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
609
}