system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CApplication

system.base
继承 abstract class CApplication » CModule » CComponent
子类 CConsoleApplication, CWebApplication
可用自 1.0
源码 framework/base/CApplication.php
CApplication 是所有应用程序类的基类。

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.

所提供的核心应用组件如下:
  • errorHandler: 处理PHP错误和错误异常。 这个应用组件在需要时动态加载。
  • securityManager: 提供安全相关的服务, 例如,哈希,加密功能。 这个应用组件在需要时动态加载。
  • statePersister: provides global state persistence method. This application component is dynamically loaded when needed.
  • cache: provides caching feature. This application component is disabled by default.
  • messages: provides the message source for translating application messages. This application component is dynamically loaded when needed.
  • coreMessages: provides the message source for translating Yii framework messages. This application component is dynamically loaded when needed.
  • urlManager: provides URL construction as well as parsing functionality. This application component is dynamically loaded when needed.
  • request: represents the current HTTP request by encapsulating the $_SERVER variable and managing cookies sent from and sent to the user. This application component is dynamically loaded when needed.
  • format: provides a set of commonly used data formatting methods. This application component is dynamically loaded when needed.


CApplication will undergo the following lifecycles when processing a user request:
  1. load application configuration;
  2. set up error handling;
  3. load static application components;
  4. onBeginRequest: preprocess the user request;
  5. processRequest: process the user request;
  6. onEndRequest: postprocess the user request;


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.

公共属性

隐藏继承的属性

属性类型描述被定义在
basePath string Returns the root path of the application. CApplication
baseUrl string Returns the relative URL for the application. CApplication
behaviors array the behaviors that should be attached to the module. CModule
cache CCache Returns the cache component. CApplication
charset string the charset currently used for the application. CApplication
components array 返回应用程序组件。 CModule
controller CController the currently active controller. CApplication
coreMessages CPhpMessageSource Returns the core message translations component. CApplication
dateFormatter CDateFormatter Returns the locale-dependent date formatter. CApplication
db CDbConnection Returns the database connection component. CApplication
errorHandler CErrorHandler Returns the error handler component. CApplication
extensionPath string Returns the root directory that holds all third-party extensions. CApplication
format CFormatter Returns the formatter component. CApplication
homeUrl string the homepage URL CApplication
id string 返回应用程序唯一的标识。 CApplication
language string Returns the language that the user is using and the application should be targeted to. CApplication
locale CLocale Returns the locale instance. CApplication
localeClass string the class used to get locale data. CApplication
localeDataPath string Returns the directory that contains the locale data. CApplication
messages CMessageSource Returns the application message translations component. CApplication
modulePath string Returns the directory that contains the application modules. CModule
modules array Returns the configuration of the currently installed modules. CModule
name string 应用程序名称。默认为 'My Application'。 CApplication
numberFormatter CNumberFormatter the locale-dependent number formatter. CApplication
params CAttributeCollection 返回用户定义的参数。 CModule
parentModule CModule 返回父模块。 CModule
preload array the IDs of the application components that should be preloaded. CModule
request CHttpRequest Returns the request component. CApplication
runtimePath string Returns the directory that stores runtime files. CApplication
securityManager CSecurityManager Returns the security manager component. CApplication
sourceLanguage string the language that the application is written in. CApplication
statePersister CStatePersister Returns the state persister component. CApplication
timeZone string Returns the time zone used by this application. CApplication
urlManager CUrlManager Returns the URL manager component. CApplication

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. CComponent
__construct() 构造器。 CApplication
__get() Getter 魔术方法。 CModule
__isset() 检查一个属性值是否为空。 CModule
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
clearGlobalState() Clears a global value. CApplication
configure() Configures the module with the specified configuration. CModule
createAbsoluteUrl() Creates an absolute URL based on the given controller and action information. CApplication
createUrl() Creates a relative URL based on the given controller and action information. CApplication
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
displayError() Displays the captured PHP error. CApplication
displayException() Displays the uncaught PHP exception. CApplication
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
end() 终止应用程序。 CApplication
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
findLocalizedFile() Returns the localized version of a specified file. CApplication
getBasePath() Returns the root path of the application. CApplication
getBaseUrl() Returns the relative URL for the application. CApplication
getCache() Returns the cache component. CApplication
getComponent() Retrieves the named application component. CModule
getComponents() 返回应用程序组件。 CModule
getController() Returns the currently active controller. Null is returned in this base class. CApplication
getCoreMessages() Returns the core message translations component. CApplication
getDateFormatter() Returns the locale-dependent date formatter. CApplication
getDb() Returns the database connection component. CApplication
getErrorHandler() Returns the error handler component. CApplication
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getExtensionPath() Returns the root directory that holds all third-party extensions. CApplication
getFormat() Returns the formatter component. CApplication
getGlobalState() Returns a global value. CApplication
getHomeUrl() Returns the homepage URL CApplication
getId() 返回应用程序唯一的标识。 CApplication
getLanguage() Returns the language that the user is using and the application should be targeted to. CApplication
getLocale() Returns the locale instance. CApplication
getLocaleDataPath() Returns the directory that contains the locale data. CApplication
getMessages() Returns the application message translations component. CApplication
getModule() 检索指定的应用程序模块。 CModule
getModulePath() Returns the directory that contains the application modules. CModule
getModules() Returns the configuration of the currently installed modules. CModule
getNumberFormatter() Returns the locale-dependent number formatter. The current application locale will be used. CApplication
getParams() 返回用户定义的参数。 CModule
getParentModule() 返回父模块。 CModule
getRequest() Returns the request component. CApplication
getRuntimePath() Returns the directory that stores runtime files. CApplication
getSecurityManager() Returns the security manager component. CApplication
getStatePersister() Returns the state persister component. CApplication
getTimeZone() Returns the time zone used by this application. CApplication
getUrlManager() Returns the URL manager component. CApplication
handleError() Handles PHP execution errors such as warnings, notices. CApplication
handleException() Handles uncaught PHP exceptions. CApplication
hasComponent() Checks whether the named component exists. CModule
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasModule() Returns a value indicating whether the specified module is installed. CModule
hasProperty() Determines whether a property is defined. CComponent
loadGlobalState() Loads the global state data from persistent storage. CApplication
onBeginRequest() Raised right BEFORE the application processes the request. CApplication
onEndRequest() Raised right AFTER the application processes the request. CApplication
onError() Raised when a PHP execution error occurs. CApplication
onException() Raised when an uncaught PHP exception occurs. CApplication
processRequest() 处理请求。 CApplication
raiseEvent() Raises an event. CComponent
run() 运行应用程序。 CApplication
saveGlobalState() Saves the global state data into persistent storage. CApplication
setAliases() Defines the root aliases. CModule
setBasePath() Sets the root directory of the application. CApplication
setComponent() Puts a component under the management of the module. CModule
setComponents() 设置应用程序组件。 CModule
setExtensionPath() Sets the root directory that holds all third-party extensions. CApplication
setGlobalState() Sets a global value. CApplication
setHomeUrl() Sets the homepage URL CApplication
setId() Sets the unique identifier for the application. CApplication
setImport() 设置用于在模块中使用的别名。 CModule
setLanguage() Specifies which language the application is targeted to. CApplication
setLocaleDataPath() Sets the directory that contains the locale data. CApplication
setModulePath() Sets the directory that contains the application modules. CModule
setModules() Configures the sub-modules of this module. CModule
setParams() 设置用户定义的参数 CModule
setRuntimePath() Sets the directory that stores runtime files. CApplication
setTimeZone() Sets the time zone used by this application. CApplication

受保护的方法

隐藏继承的方法

方法描述被定义在
init() 初始化模块。 CModule
initSystemHandlers() Initializes the error handlers. CApplication
preinit() Preinitializes the module. CModule
preloadComponents() 加载静态应用程序组件。 CModule
registerCoreComponents() Registers the core application components. CApplication

事件

隐藏继承的事件

事件描述被定义在
onBeginRequest Raised right BEFORE the application processes the request. CApplication
onEndRequest Raised right AFTER the application processes the request. CApplication
onException Raised when an uncaught PHP exception occurs. CApplication
onError Raised when a PHP execution error occurs. CApplication

属性详情

basePath 属性
public string getBasePath()
public void setBasePath(string $path)

Returns the root path of the application.

baseUrl 属性 只读
public string getBaseUrl(boolean $absolute=false)

Returns the relative URL for the application. This is a shortcut method to CHttpRequest::getBaseUrl().

cache 属性 只读
public CCache getCache()

Returns the cache component.

charset 属性
public string $charset;

the charset currently used for the application. Defaults to 'UTF-8'.

controller 属性 只读 (自版本 v1.1.8 可用)

the currently active controller. Null is returned in this base class.

coreMessages 属性 只读

Returns the core message translations component.

dateFormatter 属性 只读

Returns the locale-dependent date formatter.

db 属性 只读

Returns the database connection component.

errorHandler 属性 只读

Returns the error handler component.

extensionPath 属性
public string getExtensionPath()
public void setExtensionPath(string $path)

Returns the root directory that holds all third-party extensions.

format 属性 只读

Returns the formatter component.

homeUrl 属性
public string getHomeUrl()
public void setHomeUrl(string $value)

the homepage URL

id 属性
public string getId()
public void setId(string $id)

返回应用程序唯一的标识。

language 属性
public string getLanguage()
public void setLanguage(string $language)

Returns the language that the user is using and the application should be targeted to.

locale 属性 只读
public CLocale getLocale(string $localeID=NULL)

Returns the locale instance.

localeClass 属性
public string $localeClass;

the class used to get locale data. Defaults to 'CLocale'.

localeDataPath 属性 (自版本 v1.1.0 可用)
public string getLocaleDataPath()
public void setLocaleDataPath(string $value)

Returns the directory that contains the locale data.

messages 属性 只读

Returns the application message translations component.

name 属性
public string $name;

应用程序名称。默认为 'My Application'。

numberFormatter 属性 只读

the locale-dependent number formatter. The current application locale will be used.

request 属性 只读

Returns the request component.

runtimePath 属性
public string getRuntimePath()
public void setRuntimePath(string $path)

Returns the directory that stores runtime files.

securityManager 属性 只读

Returns the security manager component.

sourceLanguage 属性
public string $sourceLanguage;

the language that the application is written in. This mainly refers to the language that the messages and view files are in. Defaults to 'en_us' (US English).

statePersister 属性 只读

Returns the state persister component.

timeZone 属性
public string getTimeZone()
public void setTimeZone(string $value)

Returns the time zone used by this application. This is a simple wrapper of PHP function date_default_timezone_get().

urlManager 属性 只读

Returns the URL manager component.

方法详情

__construct() 方法
public void __construct(mixed $config=NULL)
$config mixed 应用程序配置。 If a string, it is treated as the path of the file that contains the configuration; If an array, it is the actual configuration information. Please make sure you specify the basePath property in the configuration, which should point to the directory containing all application logic, template and data. If not, the directory will be defaulted to 'protected'.
源码: framework/base/CApplication.php#132 (显示)
public function __construct($config=null)
{
    
Yii::setApplication($this);

    
// set basePath as early as possible to avoid trouble
    
if(is_string($config))
        
$config=require($config);
    if(isset(
$config['basePath']))
    {
        
$this->setBasePath($config['basePath']);
        unset(
$config['basePath']);
    }
    else
        
$this->setBasePath('protected');
    
Yii::setPathOfAlias('application',$this->getBasePath());
    
Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
    if(isset(
$config['extensionPath']))
    {
        
$this->setExtensionPath($config['extensionPath']);
        unset(
$config['extensionPath']);
    }
    else
        
Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
    if(isset(
$config['aliases']))
    {
        
$this->setAliases($config['aliases']);
        unset(
$config['aliases']);
    }

    
$this->preinit();

    
$this->initSystemHandlers();
    
$this->registerCoreComponents();

    
$this->configure($config);
    
$this->attachBehaviors($this->behaviors);
    
$this->preloadComponents();

    
$this->init();
}

构造器。

clearGlobalState() 方法
public void clearGlobalState(string $key)
$key string the name of the value to be cleared
源码: framework/base/CApplication.php#676 (显示)
public function clearGlobalState($key)
{
    
$this->setGlobalState($key,true,true);
}

Clears a global value.

The value cleared will no longer be available in this request and the following requests.

createAbsoluteUrl() 方法
public string createAbsoluteUrl(string $route, array $params=array ( ), string $schema='', string $ampersand='&')
$route string the URL route. This should be in the format of 'ControllerID/ActionID'.
$params array additional GET parameters (name=>value). Both the name and value will be URL-encoded.
$schema string schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
$ampersand string the token separating name-value pairs in the URL.
{return} string the constructed URL
源码: framework/base/CApplication.php#572 (显示)
public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
{
    
$url=$this->createUrl($route,$params,$ampersand);
    if(
strpos($url,'http')===|| strpos($url,'//')===0)
        return 
$url;
    else
        return 
$this->getRequest()->getHostInfo($schema).$url;
}

Creates an absolute URL based on the given controller and action information.

createUrl() 方法
public string createUrl(string $route, array $params=array ( ), string $ampersand='&')
$route string the URL route. This should be in the format of 'ControllerID/ActionID'.
$params array additional GET parameters (name=>value). Both the name and value will be URL-encoded.
$ampersand string the token separating name-value pairs in the URL.
{return} string the constructed URL
源码: framework/base/CApplication.php#559 (显示)
public function createUrl($route,$params=array(),$ampersand='&')
{
    return 
$this->getUrlManager()->createUrl($route,$params,$ampersand);
}

Creates a relative URL based on the given controller and action information.

displayError() 方法
public void displayError(integer $code, string $message, string $file, string $line)
$code integer error code
$message string error message
$file string error file
$line string error line
源码: framework/base/CApplication.php#901 (显示)
public function displayError($code,$message,$file,$line)
{
    if(
YII_DEBUG)
    {
        echo 
"<h1>PHP Error [$code]</h1>\n";
        echo 
"<p>$message ($file:$line)</p>\n";
        echo 
'<pre>';

        
$trace=debug_backtrace();
        
// skip the first 3 stacks as they do not tell the error position
        
if(count($trace)>3)
            
$trace=array_slice($trace,3);
        foreach(
$trace as $i=>$t)
        {
            if(!isset(
$t['file']))
                
$t['file']='unknown';
            if(!isset(
$t['line']))
                
$t['line']=0;
            if(!isset(
$t['function']))
                
$t['function']='unknown';
            echo 
"#$i {$t['file']}({$t['line']}): ";
            if(isset(
$t['object']) && is_object($t['object']))
                echo 
get_class($t['object']).'->';
            echo 
"{$t['function']}()\n";
        }

        echo 
'</pre>';
    }
    else
    {
        echo 
"<h1>PHP Error [$code]</h1>\n";
        echo 
"<p>$message</p>\n";
    }
}

Displays the captured PHP error. This method displays the error in HTML when there is no active error handler.

displayException() 方法
public void displayException(Exception $exception)
$exception Exception the uncaught exception
源码: framework/base/CApplication.php#942 (显示)
public function displayException($exception)
{
    if(
YII_DEBUG)
    {
        echo 
'<h1>'.get_class($exception)."</h1>\n";
        echo 
'<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
        echo 
'<pre>'.$exception->getTraceAsString().'</pre>';
    }
    else
    {
        echo 
'<h1>'.get_class($exception)."</h1>\n";
        echo 
'<p>'.$exception->getMessage().'</p>';
    }
}

Displays the uncaught PHP exception. This method displays the exception in HTML when there is no active error handler.

end() 方法
public void end(integer $status=0, boolean $exit=true)
$status integer exit status (value 0 means normal exit while other values mean abnormal exit).
$exit boolean whether to exit the current request. This parameter has been available since version 1.1.5. It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
源码: framework/base/CApplication.php#198 (显示)
public function end($status=0,$exit=true)
{
    if(
$this->hasEventHandler('onEndRequest'))
        
$this->onEndRequest(new CEvent($this));
    if(
$exit)
        exit(
$status);
}

终止应用程序。 This method replaces PHP's exit() function by calling onEndRequest before exiting.

findLocalizedFile() 方法
public string findLocalizedFile(string $srcFile, string $srcLanguage=NULL, string $language=NULL)
$srcFile string the original file
$srcLanguage string the language that the original file is in. If null, the application source language is used.
$language string the desired language that the file should be localized to. If null, the application language will be used.
{return} string the matching localized file. The original file is returned if no localized version is found or if source language is the same as the desired language.
源码: framework/base/CApplication.php#388 (显示)
public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
{
    if(
$srcLanguage===null)
        
$srcLanguage=$this->sourceLanguage;
    if(
$language===null)
        
$language=$this->getLanguage();
    if(
$language===$srcLanguage)
        return 
$srcFile;
    
$desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
    return 
is_file($desiredFile) ? $desiredFile $srcFile;
}

Returns the localized version of a specified file.

The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory named as the locale ID. For example, given the file "path/to/view.php" and locale ID "zh_cn", the localized file will be looked for as "path/to/zh_cn/view.php". If the file is not found, the original file will be returned.

For consistency, it is recommended that the locale ID is given in lower case and in the format of LanguageID_RegionID (e.g. "en_us").

getBasePath() 方法
public string getBasePath()
{return} string the root directory of the application. Defaults to 'protected'.
源码: framework/base/CApplication.php#253 (显示)
public function getBasePath()
{
    return 
$this->_basePath;
}

Returns the root path of the application.

getBaseUrl() 方法
public string getBaseUrl(boolean $absolute=false)
$absolute boolean whether to return an absolute URL. Defaults to false, meaning returning a relative one.
{return} string the relative URL for the application
源码: framework/base/CApplication.php#588 (显示)
public function getBaseUrl($absolute=false)
{
    return 
$this->getRequest()->getBaseUrl($absolute);
}

Returns the relative URL for the application. This is a shortcut method to CHttpRequest::getBaseUrl().

getCache() 方法
public CCache getCache()
{return} CCache the cache application component. Null if the component is not enabled.
源码: framework/base/CApplication.php#493 (显示)
public function getCache()
{
    return 
$this->getComponent('cache');
}

Returns the cache component.

getController() 方法 (自版本 v1.1.8 可用)
public CController getController()
{return} CController the currently active controller. Null is returned in this base class.
源码: framework/base/CApplication.php#547 (显示)
public function getController()
{
    return 
null;
}

getCoreMessages() 方法
public CPhpMessageSource getCoreMessages()
{return} CPhpMessageSource the core message translations
源码: framework/base/CApplication.php#502 (显示)
public function getCoreMessages()
{
    return 
$this->getComponent('coreMessages');
}

Returns the core message translations component.

getDateFormatter() 方法
public CDateFormatter getDateFormatter()
{return} CDateFormatter the locale-dependent date formatter. The current application locale will be used.
源码: framework/base/CApplication.php#448 (显示)
public function getDateFormatter()
{
    return 
$this->getLocale()->getDateFormatter();
}

Returns the locale-dependent date formatter.

getDb() 方法
public CDbConnection getDb()
{return} CDbConnection the database connection
源码: framework/base/CApplication.php#457 (显示)
public function getDb()
{
    return 
$this->getComponent('db');
}

Returns the database connection component.

getErrorHandler() 方法
public CErrorHandler getErrorHandler()
{return} CErrorHandler the error handler application component.
源码: framework/base/CApplication.php#466 (显示)
public function getErrorHandler()
{
    return 
$this->getComponent('errorHandler');
}

Returns the error handler component.

getExtensionPath() 方法
public string getExtensionPath()
{return} string the directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
源码: framework/base/CApplication.php#303 (显示)
public function getExtensionPath()
{
    return 
Yii::getPathOfAlias('ext');
}

Returns the root directory that holds all third-party extensions.

getFormat() 方法
public CFormatter getFormat()
{return} CFormatter the formatter component
源码: framework/base/CApplication.php#538 (显示)
public function getFormat()
{
    return 
$this->getComponent('format');
}

Returns the formatter component.

getGlobalState() 方法
public mixed getGlobalState(string $key, mixed $defaultValue=NULL)
$key string the name of the value to be returned
$defaultValue mixed the default value. If the named global value is not found, this will be returned instead.
{return} mixed the named global value
源码: framework/base/CApplication.php#626 (显示)
public function getGlobalState($key,$defaultValue=null)
{
    if(
$this->_globalState===null)
        
$this->loadGlobalState();
    if(isset(
$this->_globalState[$key]))
        return 
$this->_globalState[$key];
    else
        return 
$defaultValue;
}

Returns a global value.

A global value is one that is persistent across users sessions and requests.

getHomeUrl() 方法
public string getHomeUrl()
{return} string the homepage URL
源码: framework/base/CApplication.php#596 (显示)
public function getHomeUrl()
{
    if(
$this->_homeUrl===null)
    {
        if(
$this->getUrlManager()->showScriptName)
            return 
$this->getRequest()->getScriptUrl();
        else
            return 
$this->getRequest()->getBaseUrl().'/';
    }
    else
        return 
$this->_homeUrl;
}

getId() 方法
public string getId()
{return} string the unique identifier for the application.
源码: framework/base/CApplication.php#232 (显示)
public function getId()
{
    if(
$this->_id!==null)
        return 
$this->_id;
    else
        return 
$this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
}

返回应用程序唯一的标识。

getLanguage() 方法
public string getLanguage()
{return} string the language that the user is using and the application should be targeted to. Defaults to the source language.
源码: framework/base/CApplication.php#326 (显示)
public function getLanguage()
{
    return 
$this->_language===null $this->sourceLanguage $this->_language;
}

Returns the language that the user is using and the application should be targeted to.

getLocale() 方法
public CLocale getLocale(string $localeID=NULL)
$localeID string the locale ID (e.g. en_US). If null, the application language ID will be used.
{return} CLocale an instance of CLocale
源码: framework/base/CApplication.php#405 (显示)
public function getLocale($localeID=null)
{
    return 
call_user_func_array(array($this->localeClass'getInstance'),array($localeID===null?$this->getLanguage():$localeID));
}

Returns the locale instance.

getLocaleDataPath() 方法 (自版本 v1.1.0 可用)
public string getLocaleDataPath()
{return} string the directory that contains the locale data. It defaults to 'framework/i18n/data'.
源码: framework/base/CApplication.php#415 (显示)
public function getLocaleDataPath()
{
    
$vars=get_class_vars($this->localeClass);
    if(empty(
$vars['dataPath']))
        return 
Yii::getPathOfAlias('system.i18n.data');
    return 
$vars['dataPath'];
}

Returns the directory that contains the locale data.

getMessages() 方法
public CMessageSource getMessages()
{return} CMessageSource the application message translations
源码: framework/base/CApplication.php#511 (显示)
public function getMessages()
{
    return 
$this->getComponent('messages');
}

Returns the application message translations component.

getNumberFormatter() 方法
public CNumberFormatter getNumberFormatter()
{return} CNumberFormatter the locale-dependent number formatter. The current application locale will be used.
源码: framework/base/CApplication.php#438 (显示)
public function getNumberFormatter()
{
    return 
$this->getLocale()->getNumberFormatter();
}

getRequest() 方法
public CHttpRequest getRequest()
{return} CHttpRequest the request component
源码: framework/base/CApplication.php#520 (显示)
public function getRequest()
{
    return 
$this->getComponent('request');
}

Returns the request component.

getRuntimePath() 方法
public string getRuntimePath()
{return} string the directory that stores runtime files. Defaults to 'protected/runtime'.
源码: framework/base/CApplication.php#275 (显示)
public function getRuntimePath()
{
    if(
$this->_runtimePath!==null)
        return 
$this->_runtimePath;
    else
    {
        
$this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
        return 
$this->_runtimePath;
    }
}

Returns the directory that stores runtime files.

getSecurityManager() 方法
public CSecurityManager getSecurityManager()
{return} CSecurityManager the security manager application component.
源码: framework/base/CApplication.php#475 (显示)
public function getSecurityManager()
{
    return 
$this->getComponent('securityManager');
}

Returns the security manager component.

getStatePersister() 方法
public CStatePersister getStatePersister()
{return} CStatePersister the state persister application component.
源码: framework/base/CApplication.php#484 (显示)
public function getStatePersister()
{
    return 
$this->getComponent('statePersister');
}

Returns the state persister component.

getTimeZone() 方法
public string getTimeZone()
{return} string the time zone used by this application.
源码: framework/base/CApplication.php#353 (显示)
public function getTimeZone()
{
    return 
date_default_timezone_get();
}

Returns the time zone used by this application. This is a simple wrapper of PHP function date_default_timezone_get().

getUrlManager() 方法
public CUrlManager getUrlManager()
{return} CUrlManager the URL manager component
源码: framework/base/CApplication.php#529 (显示)
public function getUrlManager()
{
    return 
$this->getComponent('urlManager');
}

Returns the URL manager component.

handleError() 方法
public void handleError(integer $code, string $message, string $file, integer $line)
$code integer the level of the error raised
$message string the error message
$file string the filename that the error was raised in
$line integer the line number the error was raised at
源码: framework/base/CApplication.php#795 (显示)
public function handleError($code,$message,$file,$line)
{
    if(
$code error_reporting())
    {
        
// disable error capturing to avoid recursive errors
        
restore_error_handler();
        
restore_exception_handler();

        
$log="$message ($file:$line)\nStack trace:\n";
        
$trace=debug_backtrace();
        
// skip the first 3 stacks as they do not tell the error position
        
if(count($trace)>3)
            
$trace=array_slice($trace,3);
        foreach(
$trace as $i=>$t)
        {
            if(!isset(
$t['file']))
                
$t['file']='unknown';
            if(!isset(
$t['line']))
                
$t['line']=0;
            if(!isset(
$t['function']))
                
$t['function']='unknown';
            
$log.="#$i {$t['file']}({$t['line']}): ";
            if(isset(
$t['object']) && is_object($t['object']))
                
$log.=get_class($t['object']).'->';
            
$log.="{$t['function']}()\n";
        }
        if(isset(
$_SERVER['REQUEST_URI']))
            
$log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
        
Yii::log($log,CLogger::LEVEL_ERROR,'php');

        try
        {
            
Yii::import('CErrorEvent',true);
            
$event=new CErrorEvent($this,$code,$message,$file,$line);
            
$this->onError($event);
            if(!
$event->handled)
            {
                
// try an error handler
                
if(($handler=$this->getErrorHandler())!==null)
                    
$handler->handle($event);
                else
                    
$this->displayError($code,$message,$file,$line);
            }
        }
        catch(
Exception $e)
        {
            
$this->displayException($e);
        }

        try
        {
            
$this->end(1);
        }
        catch(
Exception $e)
        {
            
// use the most primitive way to log error
            
$msg get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
            
$msg .= $e->getTraceAsString()."\n";
            
$msg .= "Previous error:\n";
            
$msg .= $log."\n";
            
$msg .= '$_SERVER='.var_export($_SERVER,true);
            
error_log($msg);
            exit(
1);
        }
    }
}

Handles PHP execution errors such as warnings, notices.

This method is implemented as a PHP error handler. It requires that constant YII_ENABLE_ERROR_HANDLER be defined true.

This method will first raise an onError event. If the error is not handled by any event handler, it will call errorHandler to process the error.

The application will be terminated by this method.

handleException() 方法
public void handleException(Exception $exception)
$exception Exception exception that is not caught
源码: framework/base/CApplication.php#724 (显示)
public function handleException($exception)
{
    
// disable error capturing to avoid recursive errors
    
restore_error_handler();
    
restore_exception_handler();

    
$category='exception.'.get_class($exception);
    if(
$exception instanceof CHttpException)
        
$category.='.'.$exception->statusCode;
    
// php <5.2 doesn't support string conversion auto-magically
    
$message=$exception->__toString();
    if(isset(
$_SERVER['REQUEST_URI']))
        
$message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
    if(isset(
$_SERVER['HTTP_REFERER']))
        
$message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
    
$message.="\n---";
    
Yii::log($message,CLogger::LEVEL_ERROR,$category);

    try
    {
        
$event=new CExceptionEvent($this,$exception);
        
$this->onException($event);
        if(!
$event->handled)
        {
            
// try an error handler
            
if(($handler=$this->getErrorHandler())!==null)
                
$handler->handle($event);
            else
                
$this->displayException($exception);
        }
    }
    catch(
Exception $e)
    {
        
$this->displayException($e);
    }

    try
    {
        
$this->end(1);
    }
    catch(
Exception $e)
    {
        
// use the most primitive way to log error
        
$msg get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
        
$msg .= $e->getTraceAsString()."\n";
        
$msg .= "Previous exception:\n";
        
$msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
        
$msg .= $exception->getTraceAsString()."\n";
        
$msg .= '$_SERVER='.var_export($_SERVER,true);
        
error_log($msg);
        exit(
1);
    }
}

Handles uncaught PHP exceptions.

This method is implemented as a PHP exception handler. It requires that constant YII_ENABLE_EXCEPTION_HANDLER be defined true.

This method will first raise an onException event. If the exception is not handled by any event handler, it will call errorHandler to process the exception.

The application will be terminated by this method.

initSystemHandlers() 方法
protected void initSystemHandlers()
源码: framework/base/CApplication.php#960 (显示)
protected function initSystemHandlers()
{
    if(
YII_ENABLE_EXCEPTION_HANDLER)
        
set_exception_handler(array($this,'handleException'));
    if(
YII_ENABLE_ERROR_HANDLER)
        
set_error_handler(array($this,'handleError'),error_reporting());
}

Initializes the error handlers.

loadGlobalState() 方法
public void loadGlobalState()
源码: framework/base/CApplication.php#686 (显示)
public function loadGlobalState()
{
    
$persister=$this->getStatePersister();
    if((
$this->_globalState=$persister->load())===null)
        
$this->_globalState=array();
    
$this->_stateChanged=false;
    
$this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
}

Loads the global state data from persistent storage.

onBeginRequest() 方法
public void onBeginRequest(CEvent $event)
$event CEvent the event parameter
源码: framework/base/CApplication.php#210 (显示)
public function onBeginRequest($event)
{
    
$this->raiseEvent('onBeginRequest',$event);
}

Raised right BEFORE the application processes the request.

onEndRequest() 方法
public void onEndRequest(CEvent $event)
$event CEvent the event parameter
源码: framework/base/CApplication.php#219 (显示)
public function onEndRequest($event)
{
    if(!
$this->_ended)
    {
        
$this->_ended=true;
        
$this->raiseEvent('onEndRequest',$event);
    }
}

Raised right AFTER the application processes the request.

onError() 方法
public void onError(CErrorEvent $event)
$event CErrorEvent event parameter
源码: framework/base/CApplication.php#887 (显示)
public function onError($event)
{
    
$this->raiseEvent('onError',$event);
}

Raised when a PHP execution error occurs.

An event handler can set the handled property of the event parameter to be true to indicate no further error handling is needed. Otherwise, the errorHandler application component will continue processing the error.

onException() 方法
public void onException(CExceptionEvent $event)
$event CExceptionEvent event parameter
源码: framework/base/CApplication.php#872 (显示)
public function onException($event)
{
    
$this->raiseEvent('onException',$event);
}

Raised when an uncaught PHP exception occurs.

An event handler can set the handled property of the event parameter to be true to indicate no further error handling is needed. Otherwise, the errorHandler application component will continue processing the error.

processRequest() 方法
abstract public void processRequest()
源码: framework/base/CApplication.php#121 (显示)
abstract public function processRequest();

处理请求。 This is the place where the actual request processing work is done. Derived classes should override this method.

registerCoreComponents() 方法
protected void registerCoreComponents()
源码: framework/base/CApplication.php#972 (显示)
protected function registerCoreComponents()
{
    
$components=array(
        
'coreMessages'=>array(
            
'class'=>'CPhpMessageSource',
            
'language'=>'en_us',
            
'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
        ),
        
'db'=>array(
            
'class'=>'CDbConnection',
        ),
        
'messages'=>array(
            
'class'=>'CPhpMessageSource',
        ),
        
'errorHandler'=>array(
            
'class'=>'CErrorHandler',
        ),
        
'securityManager'=>array(
            
'class'=>'CSecurityManager',
        ),
        
'statePersister'=>array(
            
'class'=>'CStatePersister',
        ),
        
'urlManager'=>array(
            
'class'=>'CUrlManager',
        ),
        
'request'=>array(
            
'class'=>'CHttpRequest',
        ),
        
'format'=>array(
            
'class'=>'CFormatter',
        ),
    );

    
$this->setComponents($components);
}

Registers the core application components.

参见

run() 方法
public void run()
源码: framework/base/CApplication.php#180 (显示)
public function run()
{
    if(
$this->hasEventHandler('onBeginRequest'))
        
$this->onBeginRequest(new CEvent($this));
    
register_shutdown_function(array($this,'end'),0,false);
    
$this->processRequest();
    if(
$this->hasEventHandler('onEndRequest'))
        
$this->onEndRequest(new CEvent($this));
}

运行应用程序。 This method loads static application components. Derived classes usually overrides this method to do more application-specific tasks. Remember to call the parent implementation so that static application components are loaded.

saveGlobalState() 方法
public void saveGlobalState()
源码: framework/base/CApplication.php#700 (显示)
public function saveGlobalState()
{
    if(
$this->_stateChanged)
    {
        
$this->_stateChanged=false;
        
$this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
        
$this->getStatePersister()->save($this->_globalState);
    }
}

Saves the global state data into persistent storage.

setBasePath() 方法
public void setBasePath(string $path)
$path string the root directory of the application.
源码: framework/base/CApplication.php#264 (显示)
public function setBasePath($path)
{
    if((
$this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
        throw new 
CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
            array(
'{path}'=>$path)));
}

Sets the root directory of the application. This method can only be invoked at the begin of the constructor.

setExtensionPath() 方法
public void setExtensionPath(string $path)
$path string the directory that contains all third-party extensions.
源码: framework/base/CApplication.php#313 (显示)
public function setExtensionPath($path)
{
    if((
$extensionPath=realpath($path))===false || !is_dir($extensionPath))
        throw new 
CException(Yii::t('yii','Extension path "{path}" does not exist.',
            array(
'{path}'=>$path)));
    
Yii::setPathOfAlias('ext',$extensionPath);
}

Sets the root directory that holds all third-party extensions.

setGlobalState() 方法
public void setGlobalState(string $key, mixed $value, mixed $defaultValue=NULL)
$key string the name of the value to be saved
$value mixed the global value to be saved. It must be serializable.
$defaultValue mixed the default value. If the named global value is the same as this value, it will be cleared from the current storage.
源码: framework/base/CApplication.php#646 (显示)
public function setGlobalState($key,$value,$defaultValue=null)
{
    if(
$this->_globalState===null)
        
$this->loadGlobalState();

    
$changed=$this->_stateChanged;
    if(
$value===$defaultValue)
    {
        if(isset(
$this->_globalState[$key]))
        {
            unset(
$this->_globalState[$key]);
            
$this->_stateChanged=true;
        }
    }
    elseif(!isset(
$this->_globalState[$key]) || $this->_globalState[$key]!==$value)
    {
        
$this->_globalState[$key]=$value;
        
$this->_stateChanged=true;
    }

    if(
$this->_stateChanged!==$changed)
        
$this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
}

Sets a global value.

A global value is one that is persistent across users sessions and requests. Make sure that the value is serializable and unserializable.

setHomeUrl() 方法
public void setHomeUrl(string $value)
$value string the homepage URL
源码: framework/base/CApplication.php#612 (显示)
public function setHomeUrl($value)
{
    
$this->_homeUrl=$value;
}

setId() 方法
public void setId(string $id)
$id string the unique identifier for the application.
源码: framework/base/CApplication.php#244 (显示)
public function setId($id)
{
    
$this->_id=$id;
}

Sets the unique identifier for the application.

setLanguage() 方法
public void setLanguage(string $language)
$language string the user language (e.g. 'en_US', 'zh_CN'). If it is null, the sourceLanguage will be used.
源码: framework/base/CApplication.php#342 (显示)
public function setLanguage($language)
{
    
$this->_language=$language;
}

Specifies which language the application is targeted to.

This is the language that the application displays to end users. If set null, it uses the source language.

Unless your application needs to support multiple languages, you should always set this language to null to maximize the application's performance.

setLocaleDataPath() 方法 (自版本 v1.1.0 可用)
public void setLocaleDataPath(string $value)
$value string the directory that contains the locale data.
源码: framework/base/CApplication.php#428 (显示)
public function setLocaleDataPath($value)
{
    
$property=new ReflectionProperty($this->localeClass,'dataPath');
    
$property->setValue($value);
}

Sets the directory that contains the locale data.

setRuntimePath() 方法
public void setRuntimePath(string $path)
$path string the directory that stores runtime files.
源码: framework/base/CApplication.php#291 (显示)
public function setRuntimePath($path)
{
    if((
$runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
        throw new 
CException(Yii::t('yii','Application runtime path "{path}" is not valid. Please make sure it is a directory writable by the Web server process.',
            array(
'{path}'=>$path)));
    
$this->_runtimePath=$runtimePath;
}

Sets the directory that stores runtime files.

setTimeZone() 方法
public void setTimeZone(string $value)
$value string the time zone used by this application.
源码: framework/base/CApplication.php#364 (显示)
public function setTimeZone($value)
{
    
date_default_timezone_set($value);
}

Sets the time zone used by this application. This is a simple wrapper of PHP function date_default_timezone_set().