You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

455 lines
13 KiB

14 years ago
<?php
/**
* Application class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
14 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
12 years ago
use Yii;
use yii\util\FileHelper;
13 years ago
14 years ago
/**
* Application is the base class for all application classes.
*
* An application serves as the global context that the user request
* is being processed. It manages a set of application components that
* provide specific functionalities to the whole application.
*
* The core application components provided by Application are the following:
* <ul>
* <li>{@link getErrorHandler errorHandler}: handles PHP errors and
* uncaught exceptions. This application component is dynamically loaded when needed.</li>
* <li>{@link getSecurityManager securityManager}: provides security-related
* services, such as hashing, encryption. This application component is dynamically
* loaded when needed.</li>
* <li>{@link getStatePersister statePersister}: provides global state
* persistence method. This application component is dynamically loaded when needed.</li>
* <li>{@link getCache cache}: provides caching feature. This application component is
* disabled by default.</li>
* </ul>
*
* Application will undergo the following life cycles when processing a user request:
14 years ago
* <ol>
* <li>load application configuration;</li>
* <li>set up class autoloader and error handling;</li>
* <li>load static application components;</li>
* <li>{@link beforeRequest}: preprocess the user request; `beforeRequest` event raised.</li>
14 years ago
* <li>{@link processRequest}: process the user request;</li>
* <li>{@link afterRequest}: postprocess the user request; `afterRequest` event raised.</li>
14 years ago
* </ol>
*
* Starting from lifecycle 3, if a PHP error or an uncaught exception occurs,
* the application will switch to its error handling logic and jump to step 6 afterwards.
*
14 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
14 years ago
*/
13 years ago
class Application extends Module
14 years ago
{
const EVENT_BEFORE_REQUEST = 'beforeRequest';
const EVENT_AFTER_REQUEST = 'afterRequest';
14 years ago
/**
* @var string the application name.
14 years ago
*/
public $name = 'My Application';
/**
* @var string the version of this application.
13 years ago
*/
public $version = '1.0';
/**
* @var string the charset currently used for the application.
14 years ago
*/
public $charset = 'UTF-8';
/**
* @var string the language that is meant to be used for end users.
* @see sourceLanguage
*/
public $language = 'en_US';
/**
14 years ago
* @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.
13 years ago
* @see language
14 years ago
*/
public $sourceLanguage = 'en_US';
13 years ago
/**
* @var array IDs of the components that need to be loaded when the application starts.
13 years ago
*/
public $preload = array();
/**
* @var Controller the currently active controller instance
*/
public $controller;
13 years ago
/**
* @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';
14 years ago
// todo
13 years ago
public $localeDataPath = '@yii/i18n/data';
14 years ago
private $_runtimePath;
private $_ended = false;
private $_language;
/**
* Constructor.
13 years ago
* @param string $id the ID of this application. The ID should uniquely identify the application from others.
13 years ago
* @param string $basePath the base path of this application. This should point to
* the directory containing all application logic, template and data.
* @param array $config name-value pairs that will be used to initialize the object properties
14 years ago
*/
public function __construct($id, $basePath, $config = array())
14 years ago
{
Yii::$app = $this;
13 years ago
$this->id = $id;
13 years ago
$this->setBasePath($basePath);
if (YII_ENABLE_ERROR_HANDLER) {
set_exception_handler(array($this, 'handleException'));
set_error_handler(array($this, 'handleError'), error_reporting());
}
13 years ago
$this->registerDefaultAliases();
14 years ago
$this->registerCoreComponents();
Component::__construct($config);
13 years ago
}
14 years ago
13 years ago
/**
* Initializes the application by loading components declared in [[preload]].
* If you override this method, make sure the parent implementation is invoked.
13 years ago
*/
public function init()
{
14 years ago
$this->preloadComponents();
}
/**
* Terminates the application.
13 years ago
* This method replaces PHP's exit() function by calling [[afterRequest()]] before exiting.
14 years ago
* @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
13 years ago
* @param boolean $exit whether to exit the current request.
14 years ago
* 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)
{
13 years ago
if (!$this->_ended) {
$this->_ended = true;
$this->afterRequest();
13 years ago
}
if ($exit) {
14 years ago
exit($status);
13 years ago
}
14 years ago
}
/**
13 years ago
* 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();
$status = $this->processRequest();
$this->afterRequest();
return $status;
}
/**
12 years ago
* Raises the [[EVENT_BEFORE_REQUEST]] event right BEFORE the application processes the request.
14 years ago
*/
13 years ago
public function beforeRequest()
14 years ago
{
$this->trigger(self::EVENT_BEFORE_REQUEST);
14 years ago
}
/**
12 years ago
* Raises the [[EVENT_AFTER_REQUEST]] event right AFTER the application processes the request.
13 years ago
*/
public function afterRequest()
13 years ago
{
$this->trigger(self::EVENT_AFTER_REQUEST);
13 years ago
}
/**
* Processes the request.
13 years ago
* Child classes should override this method with actual request processing logic.
* @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
13 years ago
*/
public function processRequest()
{
return 0;
}
/**
14 years ago
* Returns the directory that stores runtime files.
* @return string the directory that stores runtime files. Defaults to 'protected/runtime'.
*/
public function getRuntimePath()
{
13 years ago
if ($this->_runtimePath !== null) {
14 years ago
$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
}
return $this->_runtimePath;
14 years ago
}
/**
* Sets the directory that stores runtime files.
* @param string $path the directory that stores runtime files.
* @throws InvalidConfigException if the directory does not exist or is not writable
14 years ago
*/
public function setRuntimePath($path)
{
$p = FileHelper::ensureDirectory($path);
if (is_writable($p)) {
13 years ago
$this->_runtimePath = $p;
} else {
throw new InvalidConfigException("Runtime path must be writable by the Web server process: $path");
13 years ago
}
14 years ago
}
/**
* Returns the time zone used by this application.
* This is a simple wrapper of PHP function date_default_timezone_get().
* @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 security manager component.
// * @return SecurityManager the security manager application component.
// */
// public function getSecurityManager()
// {
// return $this->getComponent('securityManager');
// }
//
// /**
// * Returns the locale instance.
// * @param string $localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
// * @return CLocale the locale instance
// */
// public function getLocale($localeID = null)
// {
// return CLocale::getInstance($localeID === null ? $this->getLanguage() : $localeID);
// }
//
// /**
// * @return CNumberFormatter the locale-dependent number formatter.
// * The current {@link getLocale application locale} will be used.
// */
// public function getNumberFormatter()
// {
// return $this->getLocale()->getNumberFormatter();
// }
//
// /**
// * Returns the locale-dependent date formatter.
// * @return CDateFormatter the locale-dependent date formatter.
// * The current {@link getLocale application locale} will be used.
// */
// public function getDateFormatter()
// {
// return $this->getLocale()->getDateFormatter();
// }
//
14 years ago
/**
* Returns the database connection component.
* @return \yii\db\Connection the database connection
14 years ago
*/
public function getDb()
{
return $this->getComponent('db');
}
/**
* Returns the error handler component.
13 years ago
* @return ErrorHandler the error handler application component.
14 years ago
*/
public function getErrorHandler()
{
return $this->getComponent('errorHandler');
}
/**
13 years ago
* Returns the application theme.
* @return Theme the theme that this application is currently using.
*/
public function getTheme()
{
return $this->getComponent('theme');
}
/**
14 years ago
* Returns the cache component.
13 years ago
* @return \yii\caching\Cache the cache application component. Null if the component is not enabled.
14 years ago
*/
public function getCache()
{
return $this->getComponent('cache');
}
/**
* Returns the request component.
13 years ago
* @return Request the request component
14 years ago
*/
public function getRequest()
{
return $this->getComponent('request');
}
/**
12 years ago
* Returns the view renderer.
* @return ViewRenderer the view renderer used by this application.
*/
public function getViewRenderer()
{
return $this->getComponent('viewRenderer');
}
/**
* Returns the internationalization (i18n) component
* @return \yii\i18n\I18N the internationalization component
*/
public function getI18N()
{
return $this->getComponent('i18n');
}
/**
13 years ago
* Sets default path aliases.
*/
public function registerDefaultAliases()
{
Yii::$aliases['@app'] = $this->getBasePath();
12 years ago
Yii::$aliases['@entry'] = dirname($_SERVER['SCRIPT_FILENAME']);
Yii::$aliases['@www'] = '';
13 years ago
}
/**
14 years ago
* Registers the core application components.
* @see setComponents
*/
13 years ago
public function registerCoreComponents()
14 years ago
{
13 years ago
$this->setComponents(array(
'errorHandler' => array(
'class' => 'yii\base\ErrorHandler',
),
'i18n' => array(
'class' => 'yii\i18n\I18N',
14 years ago
),
'securityManager' => array(
13 years ago
'class' => 'yii\base\SecurityManager',
14 years ago
),
13 years ago
));
14 years ago
}
/**
* 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
* @throws \ErrorException the error exception
*/
public function handleError($code, $message, $file, $line)
{
if (error_reporting() !== 0) {
throw new \ErrorException($message, 0, $code, $file, $line);
}
}
/**
* 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;
$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
error_log($msg);
exit(1);
}
}
/**
* Renders an exception without using rich format.
* @param \Exception $exception the exception to be rendered.
*/
public function renderException($exception)
{
if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
$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>';
}
}
// 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);
}
14 years ago
}