Application.php 12.3 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.
 *
w  
Qiang Xue committed
15 16
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
w  
Qiang Xue committed
17
 */
Qiang Xue committed
18
class Application extends Module
w  
Qiang Xue committed
19
{
Qiang Xue committed
20 21
	const EVENT_BEFORE_REQUEST = 'beforeRequest';
	const EVENT_AFTER_REQUEST = 'afterRequest';
w  
Qiang Xue committed
22
	/**
Qiang Xue committed
23
	 * @var string the application name.
w  
Qiang Xue committed
24 25
	 */
	public $name = 'My Application';
Qiang Xue committed
26
	/**
Qiang Xue committed
27
	 * @var string the version of this application.
Qiang Xue committed
28 29
	 */
	public $version = '1.0';
w  
Qiang Xue committed
30
	/**
Qiang Xue committed
31
	 * @var string the charset currently used for the application.
w  
Qiang Xue committed
32 33
	 */
	public $charset = 'UTF-8';
Qiang Xue committed
34 35 36 37 38
	/**
	 * @var string the language that is meant to be used for end users.
	 * @see sourceLanguage
	 */
	public $language = 'en_US';
w  
Qiang Xue committed
39 40
	/**
	 * @var string the language that the application is written in. This mainly refers to
Qiang Xue committed
41
	 * the language that the messages and view files are written in.
.  
Qiang Xue committed
42
	 * @see language
w  
Qiang Xue committed
43
	 */
Qiang Xue committed
44
	public $sourceLanguage = 'en_US';
Qiang Xue committed
45
	/**
Qiang Xue committed
46
	 * @var array IDs of the components that need to be loaded when the application starts.
Qiang Xue committed
47
	 */
Qiang Xue committed
48
	public $preload = array();
Qiang Xue committed
49
	/**
50
	 * @var \yii\web\Controller|\yii\console\Controller the currently active controller instance
Qiang Xue committed
51 52
	 */
	public $controller;
Qiang Xue committed
53 54 55 56 57
	/**
	 * @var mixed 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';
w  
Qiang Xue committed
58 59 60

	private $_ended = false;

61
	/**
Alexander Makarov committed
62
	 * @var string Used to reserve memory for fatal error handler.
63 64 65
	 */
	private $_memoryReserve;

w  
Qiang Xue committed
66 67
	/**
	 * Constructor.
68 69 70
	 * @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]].
	 * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
w  
Qiang Xue committed
71
	 */
72
	public function __construct($config = array())
w  
Qiang Xue committed
73
	{
Qiang Xue committed
74
		Yii::$app = $this;
75 76 77 78 79 80 81

		if (!isset($config['id'])) {
			throw new InvalidConfigException('The "id" configuration is required.');
		}

		if (isset($config['basePath'])) {
			$this->setBasePath($config['basePath']);
Qiang Xue committed
82
			Yii::setAlias('@app', $this->getBasePath());
83 84 85 86
			unset($config['basePath']);
		} else {
			throw new InvalidConfigException('The "basePath" configuration is required.');
		}
87
		
88 89 90 91 92 93
		if (isset($config['timeZone'])) {
			$this->setTimeZone($config['timeZone']);
			unset($config['timeZone']);
		} elseif (!ini_get('date.timezone')) {
			$this->setTimeZone('UTC');
		} 
Qiang Xue committed
94

Qiang Xue committed
95
		$this->registerErrorHandlers();
w  
Qiang Xue committed
96
		$this->registerCoreComponents();
Qiang Xue committed
97

Qiang Xue committed
98
		Component::__construct($config);
.  
Qiang Xue committed
99
	}
w  
Qiang Xue committed
100

.  
Qiang Xue committed
101
	/**
Qiang Xue committed
102
	 * Registers error handlers.
.  
Qiang Xue committed
103
	 */
Qiang Xue committed
104
	public function registerErrorHandlers()
.  
Qiang Xue committed
105
	{
Qiang Xue committed
106 107 108 109 110
		if (YII_ENABLE_ERROR_HANDLER) {
			ini_set('display_errors', 0);
			set_exception_handler(array($this, 'handleException'));
			set_error_handler(array($this, 'handleError'), error_reporting());
		}
w  
Qiang Xue committed
111 112 113 114
	}

	/**
	 * Terminates the application.
.  
Qiang Xue committed
115
	 * This method replaces PHP's exit() function by calling [[afterRequest()]] before exiting.
w  
Qiang Xue committed
116
	 * @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
.  
Qiang Xue committed
117
	 * @param boolean $exit whether to exit the current request.
w  
Qiang Xue committed
118 119 120 121
	 * It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
	 */
	public function end($status = 0, $exit = true)
	{
.  
Qiang Xue committed
122 123 124
		if (!$this->_ended) {
			$this->_ended = true;
			$this->afterRequest();
Qiang Xue committed
125
		}
126

127 128 129 130 131 132 133
		$this->handleFatalError();

		if ($exit) {
			exit($status);
		}
	}

Qiang Xue committed
134 135 136 137 138 139 140 141
	/**
	 * 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()
	{
		$this->beforeRequest();
142 143
		// Allocating twice more than required to display memory exhausted error
		// in case of trying to allocate last 1 byte while all memory is taken.
Qiang Xue committed
144 145
		$this->_memoryReserve = str_repeat('x', 1024 * 256);
		register_shutdown_function(array($this, 'end'), 0, false);
Qiang Xue committed
146 147 148 149 150
		$status = $this->processRequest();
		$this->afterRequest();
		return $status;
	}

w  
Qiang Xue committed
151
	/**
Qiang Xue committed
152
	 * Raises the [[EVENT_BEFORE_REQUEST]] event right BEFORE the application processes the request.
w  
Qiang Xue committed
153
	 */
.  
Qiang Xue committed
154
	public function beforeRequest()
w  
Qiang Xue committed
155
	{
Qiang Xue committed
156
		$this->trigger(self::EVENT_BEFORE_REQUEST);
w  
Qiang Xue committed
157 158
	}

Qiang Xue committed
159
	/**
Qiang Xue committed
160
	 * Raises the [[EVENT_AFTER_REQUEST]] event right AFTER the application processes the request.
Qiang Xue committed
161
	 */
Qiang Xue committed
162
	public function afterRequest()
Qiang Xue committed
163
	{
Qiang Xue committed
164
		$this->trigger(self::EVENT_AFTER_REQUEST);
Qiang Xue committed
165 166
	}

w  
Qiang Xue committed
167
	/**
Qiang Xue committed
168
	 * Processes the request.
Qiang Xue committed
169
	 * Child classes should override this method with actual request processing logic.
Qiang Xue committed
170
	 * @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
Qiang Xue committed
171 172 173 174 175 176
	 */
	public function processRequest()
	{
		return 0;
	}

Qiang Xue committed
177 178
	private $_runtimePath;

w  
Qiang Xue committed
179 180 181 182 183 184
	/**
	 * Returns the directory that stores runtime files.
	 * @return string the directory that stores runtime files. Defaults to 'protected/runtime'.
	 */
	public function getRuntimePath()
	{
Qiang Xue committed
185
		if ($this->_runtimePath === null) {
w  
Qiang Xue committed
186 187
			$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
		}
Qiang Xue committed
188
		return $this->_runtimePath;
w  
Qiang Xue committed
189 190 191 192 193
	}

	/**
	 * Sets the directory that stores runtime files.
	 * @param string $path the directory that stores runtime files.
Qiang Xue committed
194
	 * @throws InvalidConfigException if the directory does not exist or is not writable
w  
Qiang Xue committed
195 196 197
	 */
	public function setRuntimePath($path)
	{
Qiang Xue committed
198 199 200
		$path = Yii::getAlias($path);
		if (is_dir($path) && is_writable($path)) {
			$this->_runtimePath = $path;
Qiang Xue committed
201
		} else {
Qiang Xue committed
202
			throw new InvalidConfigException("Runtime path must be a directory writable by the Web server process: $path");
Qiang Xue committed
203
		}
w  
Qiang Xue committed
204 205
	}

Qiang Xue committed
206 207 208 209 210 211 212 213
	private $_vendorPath;

	/**
	 * Returns the directory that stores vendor files.
	 * @return string the directory that stores vendor files. Defaults to 'protected/vendor'.
	 */
	public function getVendorPath()
	{
Qiang Xue committed
214
		if ($this->_vendorPath === null) {
Qiang Xue committed
215 216 217 218 219 220 221 222 223 224 225
			$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)
	{
Qiang Xue committed
226
		$this->_vendorPath = Yii::getAlias($path);
Qiang Xue committed
227 228
	}

w  
Qiang Xue committed
229 230 231
	/**
	 * Returns the time zone used by this application.
	 * This is a simple wrapper of PHP function date_default_timezone_get().
232 233
	 * If time zone is not configured in php.ini or application config,
	 * it will be set to UTC by default.
w  
Qiang Xue committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
	 * @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().
	 * @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.
Qiang Xue committed
255
	 * @return \yii\db\Connection the database connection
w  
Qiang Xue committed
256 257 258 259 260 261 262 263
	 */
	public function getDb()
	{
		return $this->getComponent('db');
	}

	/**
	 * Returns the error handler component.
.  
Qiang Xue committed
264
	 * @return ErrorHandler the error handler application component.
w  
Qiang Xue committed
265 266 267 268 269 270 271 272
	 */
	public function getErrorHandler()
	{
		return $this->getComponent('errorHandler');
	}

	/**
	 * Returns the cache component.
.  
Qiang Xue committed
273
	 * @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
w  
Qiang Xue committed
274 275 276 277 278 279 280 281
	 */
	public function getCache()
	{
		return $this->getComponent('cache');
	}

	/**
	 * Returns the request component.
282
	 * @return \yii\web\Request|\yii\console\Request the request component
w  
Qiang Xue committed
283 284 285 286 287 288
	 */
	public function getRequest()
	{
		return $this->getComponent('request');
	}

Qiang Xue committed
289
	/**
Qiang Xue committed
290 291
	 * Returns the view object.
	 * @return View the view object that is used to render various view files.
Qiang Xue committed
292
	 */
Qiang Xue committed
293
	public function getView()
Qiang Xue committed
294
	{
Qiang Xue committed
295
		return $this->getComponent('view');
Qiang Xue committed
296 297
	}

Qiang Xue committed
298 299 300 301 302 303 304 305 306
	/**
	 * Returns the URL manager for this application.
	 * @return \yii\web\UrlManager the URL manager for this application.
	 */
	public function getUrlManager()
	{
		return $this->getComponent('urlManager');
	}

Qiang Xue committed
307 308 309 310 311 312 313 314 315
	/**
	 * Returns the internationalization (i18n) component
	 * @return \yii\i18n\I18N the internationalization component
	 */
	public function getI18N()
	{
		return $this->getComponent('i18n');
	}

Qiang Xue committed
316
	/**
317
	 * Returns the auth manager for this application.
318
	 * @return \yii\rbac\Manager the auth manager for this application.
Qiang Xue committed
319 320 321
	 */
	public function getAuthManager()
	{
322
		return $this->getComponent('authManager');
Qiang Xue committed
323 324
	}

w  
Qiang Xue committed
325 326 327 328
	/**
	 * Registers the core application components.
	 * @see setComponents
	 */
.  
Qiang Xue committed
329
	public function registerCoreComponents()
w  
Qiang Xue committed
330
	{
.  
Qiang Xue committed
331 332 333 334
		$this->setComponents(array(
			'errorHandler' => array(
				'class' => 'yii\base\ErrorHandler',
			),
Qiang Xue committed
335 336
			'i18n' => array(
				'class' => 'yii\i18n\I18N',
w  
Qiang Xue committed
337
			),
Qiang Xue committed
338 339
			'urlManager' => array(
				'class' => 'yii\web\UrlManager',
w  
Qiang Xue committed
340
			),
Qiang Xue committed
341 342 343
			'view' => array(
				'class' => 'yii\base\View',
			),
.  
Qiang Xue committed
344
		));
w  
Qiang Xue committed
345
	}
Qiang Xue committed
346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
	/**
	 * Handles uncaught PHP exceptions.
	 *
	 * This method is implemented as a PHP exception handler. It requires
	 * that constant YII_ENABLE_ERROR_HANDLER be defined true.
	 *
	 * @param \Exception $exception exception that is not caught
	 */
	public function handleException($exception)
	{
		// disable error capturing to avoid recursive errors while handling exceptions
		restore_error_handler();
		restore_exception_handler();

		try {
			$this->logException($exception);

			if (($handler = $this->getErrorHandler()) !== null) {
				$handler->handle($exception);
			} else {
				$this->renderException($exception);
			}

			$this->end(1);

		} catch (\Exception $e) {
			// exception could be thrown in end() or ErrorHandler::handle()
			$msg = (string)$e;
			$msg .= "\nPrevious exception:\n";
			$msg .= (string)$exception;
			if (YII_DEBUG) {
				echo $msg;
			}
			$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
			error_log($msg);
			exit(1);
		}
	}

Qiang Xue committed
386 387 388 389 390 391 392 393 394
	/**
	 * Handles PHP execution errors such as warnings, notices.
	 *
	 * This method is used as a PHP error handler. It will simply raise an `ErrorException`.
	 *
	 * @param integer $code the level of the error raised
	 * @param string $message the error message
	 * @param string $file the filename that the error was raised in
	 * @param integer $line the line number the error was raised at
395 396
	 *
	 * @throws ErrorException
Qiang Xue committed
397 398 399 400
	 */
	public function handleError($code, $message, $file, $line)
	{
		if (error_reporting() !== 0) {
401 402 403 404 405
			$exception = new ErrorException($message, $code, $code, $file, $line);

			// in case error appeared in __toString method we can't throw any exception
			$trace = debug_backtrace(false);
			array_shift($trace);
Qiang Xue committed
406 407
			foreach ($trace as $frame) {
				if ($frame['function'] == '__toString') {
408 409 410 411 412
					$this->handleException($exception);
				}
			}

			throw $exception;
Qiang Xue committed
413 414 415 416
		}
	}

	/**
417
	 * Handles fatal PHP errors
Qiang Xue committed
418
	 */
419
	public function handleFatalError()
Qiang Xue committed
420
	{
421 422
		if (YII_ENABLE_ERROR_HANDLER) {
			$error = error_get_last();
Qiang Xue committed
423

424 425 426 427 428
			if (ErrorException::isFatalError($error)) {
				unset($this->_memoryReserve);
				$exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
				// use error_log because it's too late to use Yii log
				error_log($exception);
Qiang Xue committed
429

430
				if (($handler = $this->getErrorHandler()) !== null) {
431
					$handler->handle($exception);
432 433 434
				} else {
					$this->renderException($exception);
				}
Qiang Xue committed
435

436
				exit(1);
Qiang Xue committed
437
			}
Qiang Xue committed
438 439 440
		}
	}

Qiang Xue committed
441 442 443 444 445 446
	/**
	 * Renders an exception without using rich format.
	 * @param \Exception $exception the exception to be rendered.
	 */
	public function renderException($exception)
	{
Qiang Xue committed
447
		if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
Qiang Xue committed
448 449 450 451 452 453 454 455 456 457 458
			$message = $exception->getName() . ': ' . $exception->getMessage();
		} else {
			$message = YII_DEBUG ? (string)$exception : 'Error: ' . $exception->getMessage();
		}
		if (PHP_SAPI) {
			echo $message . "\n";
		} else {
			echo '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
		}
	}

Qiang Xue committed
459 460 461 462 463 464 465 466 467 468 469 470 471
	// todo: to be polished
	protected function logException($exception)
	{
		$category = get_class($exception);
		if ($exception instanceof HttpException) {
			/** @var $exception HttpException */
			$category .= '\\' . $exception->statusCode;
		} elseif ($exception instanceof \ErrorException) {
			/** @var $exception \ErrorException */
			$category .= '\\' . $exception->getSeverity();
		}
		Yii::error((string)$exception, $category);
	}
w  
Qiang Xue committed
472
}