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

YiiBase

system
继承 class YiiBase
子类 Yii
可用自 1.0
源码 framework/YiiBase.php
YiiBase is a helper class serving common framework functionalities.

Do not use YiiBase directly. Instead, use its child class Yii where you can customize methods of YiiBase.

公共属性

隐藏继承的属性

属性类型描述被定义在
autoloaderFilters array filters for autoloading mechanism. YiiBase
classMap array class map used by the Yii autoloading mechanism. YiiBase
enableIncludePath boolean whether to rely on PHP include path to autoload class files. YiiBase

公共方法

隐藏继承的方法

方法描述被定义在
app() Returns the application singleton or null if the singleton has not been created yet. YiiBase
autoload() Class autoload loader. YiiBase
beginProfile() Marks the beginning of a code block for profiling. YiiBase
createApplication() Creates an application of the specified class. YiiBase
createComponent() Creates an object and initializes it based on the given configuration. YiiBase
createConsoleApplication() Creates a console application instance. YiiBase
createWebApplication() Creates a Web application instance. YiiBase
endProfile() Marks the end of a code block for profiling. YiiBase
getFrameworkPath() Returns the path of the framework YiiBase
getLogger() Returns message logger YiiBase
getPathOfAlias() Translates an alias into a file path. YiiBase
getVersion() Returns the version of Yii framework YiiBase
import() Imports a class or a directory. YiiBase
log() Logs a message. YiiBase
powered() Returns a string that can be displayed on your Web page showing Powered-by-Yii information YiiBase
registerAutoloader() Registers a new class autoloader. YiiBase
setApplication() Stores the application instance in the class static member. YiiBase
setLogger() Sets the logger object. YiiBase
setPathOfAlias() Create a path alias. YiiBase
t() Translates a message to the specified language. YiiBase
trace() Writes a trace message. YiiBase

属性详情

autoloaderFilters 属性 (自版本 v1.1.20 可用)
public static array $autoloaderFilters;

filters for autoloading mechanism. It should be callable. For callable function autoloader pass className. If filter function returns true Yii autoloader will be skipped.

classMap 属性 (自版本 v1.1.5 可用)
public static array $classMap;

class map used by the Yii autoloading mechanism. The array keys are the class names and the array values are the corresponding class file paths.

enableIncludePath 属性 (自版本 v1.1.8 可用)
public static boolean $enableIncludePath;

whether to rely on PHP include path to autoload class files. Defaults to true. You may set this to be false if your hosting environment doesn't allow changing the PHP include path, or if you want to append additional autoloaders to the default Yii autoloader.

方法详情

app() 方法
public static CApplication app()
{return} CApplication the application singleton, null if the singleton has not been created yet.
源码: framework/YiiBase.php#139 (显示)
public static function app()
{
    return 
self::$_app;
}

Returns the application singleton or null if the singleton has not been created yet.

autoload() 方法
public static boolean autoload(string $className, bool $classMapOnly=false)
$className string class name
$classMapOnly bool whether to load classes via classmap only
{return} boolean whether the class has been loaded successfully
源码: framework/YiiBase.php#407 (显示)
public static function autoload($className,$classMapOnly=false)
{
    foreach (
self::$autoloaderFilters as $filter)
    {
        if (
is_array($filter)
            && isset(
$filter[0]) && isset($filter[1])
            && 
is_string($filter[0]) && is_string($filter[1])
            && 
true === call_user_func(array($filter[0], $filter[1]), $className)
        )
        {
            return 
true;
        }
        elseif (
is_string($filter)
            && 
true === call_user_func($filter$className)
        )
        {
            return 
true;
        }
        elseif (
is_callable($filter)
            && 
true === $filter($className)
        )
        {
            return 
true;
        }
    }

    
// use include so that the error PHP file may appear
    
if(isset(self::$classMap[$className]))
        include(
self::$classMap[$className]);
    elseif(isset(
self::$_coreClasses[$className]))
        include(
YII_PATH.self::$_coreClasses[$className]);
    elseif(
$classMapOnly)
        return 
false;
    else
    {
        
// include class file relying on include_path
        
if(strpos($className,'\\')===false)  // class without namespace
        
{
            if(
self::$enableIncludePath===false)
            {
                foreach(
self::$_includePaths as $path)
                {
                    
$classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
                    if(
is_file($classFile))
                    {
                        include(
$classFile);
                        if(
YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
                            throw new 
CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
                                
'{class}'=>$className,
                                
'{file}'=>$classFile,
                            )));
                        break;
                    }
                }
            }
            else
                include(
$className.'.php');
        }
        else  
// class name with namespace in PHP 5.3
        
{
            
$namespace=str_replace('\\','.',ltrim($className,'\\'));
            if((
$path=self::getPathOfAlias($namespace))!==false && is_file($path.'.php'))
                include(
$path.'.php');
            else
                return 
false;
        }
        return 
class_exists($className,false) || interface_exists($className,false);
    }
    return 
true;
}

Class autoload loader. This method is provided to be invoked within an __autoload() magic method.

beginProfile() 方法
public static void beginProfile(string $token, string $category='application')
$token string token for the code block
$category string the category of this log message
源码: framework/YiiBase.php#542 (显示)
public static function beginProfile($token,$category='application')
{
    
self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
}

Marks the beginning of a code block for profiling. This has to be matched with a call to endProfile() with the same token. The begin- and end- calls must also be properly nested, e.g.,

Yii::beginProfile('block1');
Yii::beginProfile('block2');
Yii::endProfile('block2');
Yii::endProfile('block1');
The following sequence is not valid:
Yii::beginProfile('block1');
Yii::beginProfile('block2');
Yii::endProfile('block1');
Yii::endProfile('block2');

参见

createApplication() 方法
public static mixed createApplication(string $class, mixed $config=NULL)
$class string the application class name
$config mixed application configuration. This parameter will be passed as the parameter to the constructor of the application class.
{return} mixed the application instance
源码: framework/YiiBase.php#130 (显示)
public static function createApplication($class,$config=null)
{
    return new 
$class($config);
}

Creates an application of the specified class.

createComponent() 方法
public static mixed createComponent(mixed $config)
$config mixed the configuration. It can be either a string or an array.
{return} mixed the created object
源码: framework/YiiBase.php#187 (显示)
public static function createComponent($config)
{
    
$args func_get_args();
    if(
is_string($config))
    {
        
$type=$config;
        
$config=array();
    }
    elseif(isset(
$config['class']))
    {
        
$type=$config['class'];
        unset(
$config['class']);
    }
    else
        throw new 
CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));

    if(!
class_exists($type,false))
        
$type=Yii::import($type,true);

    if((
$n=func_num_args())>1)
    {
        if(
$n===2)
            
$object=new $type($args[1]);
        elseif(
$n===3)
            
$object=new $type($args[1],$args[2]);
        elseif(
$n===4)
            
$object=new $type($args[1],$args[2],$args[3]);
        else
        {
            unset(
$args[0]);
            
$class=new ReflectionClass($type);
            
// Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
            // $object=$class->newInstanceArgs($args);
            
$object=call_user_func_array(array($class,'newInstance'),$args);
        }
    }
    else
        
$object=new $type;

    foreach(
$config as $key=>$value)
        
$object->$key=$value;

    return 
$object;
}

Creates an object and initializes it based on the given configuration.

The specified configuration can be either a string or an array. If the former, the string is treated as the object type which can be either the class name or class path alias. If the latter, the 'class' element is treated as the object type, and the rest of the name-value pairs in the array are used to initialize the corresponding object properties.

Any additional parameters passed to this method will be passed to the constructor of the object being created.

createConsoleApplication() 方法
public static CConsoleApplication createConsoleApplication(mixed $config=NULL)
$config mixed application configuration. 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'.
{return} CConsoleApplication
源码: framework/YiiBase.php#118 (显示)
public static function createConsoleApplication($config=null)
{
    return 
self::createApplication('CConsoleApplication',$config);
}

Creates a console application instance.

createWebApplication() 方法
public static CWebApplication createWebApplication(mixed $config=NULL)
$config mixed application configuration. 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'.
{return} CWebApplication
源码: framework/YiiBase.php#103 (显示)
public static function createWebApplication($config=null)
{
    return 
self::createApplication('CWebApplication',$config);
}

Creates a Web application instance.

endProfile() 方法
public static void endProfile(string $token, string $category='application')
$token string token for the code block
$category string the category of this log message
源码: framework/YiiBase.php#554 (显示)
public static function endProfile($token,$category='application')
{
    
self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
}

Marks the end of a code block for profiling. This has to be matched with a previous call to beginProfile() with the same token.

参见

getFrameworkPath() 方法
public static string getFrameworkPath()
{return} string the path of the framework
源码: framework/YiiBase.php#165 (显示)
public static function getFrameworkPath()
{
    return 
YII_PATH;
}

getLogger() 方法
public static CLogger getLogger()
{return} CLogger message logger
源码: framework/YiiBase.php#562 (显示)
public static function getLogger()
{
    if(
self::$_logger!==null)
        return 
self::$_logger;
    else
        return 
self::$_logger=new CLogger;
}

getPathOfAlias() 方法
public static mixed getPathOfAlias(string $alias)
$alias string alias (e.g. system.web.CController)
{return} mixed file path corresponding to the alias, false if the alias is invalid.
源码: framework/YiiBase.php#366 (显示)
public static function getPathOfAlias($alias)
{
    if(isset(
self::$_aliases[$alias]))
        return 
self::$_aliases[$alias];
    elseif((
$pos=strpos($alias,'.'))!==false)
    {
        
$rootAlias=substr($alias,0,$pos);
        if(isset(
self::$_aliases[$rootAlias]))
            return 
self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
        elseif(
self::$_app instanceof CWebApplication)
        {
            if(
self::$_app->findModule($rootAlias)!==null)
                return 
self::getPathOfAlias($alias);
        }
    }
    return 
false;
}

Translates an alias into a file path. Note, this method does not ensure the existence of the resulting file path. It only checks if the root alias is valid or not.

getVersion() 方法
public static string getVersion()
{return} string the version of Yii framework
源码: framework/YiiBase.php#88 (显示)
public static function getVersion()
{
    return 
'1.1.21-dev';
}

import() 方法
public static string import(string $alias, boolean $forceInclude=false)
$alias string path alias to be imported
$forceInclude boolean whether to include the class file immediately. If false, the class file will be included only when the class is being used. This parameter is used only when the path alias refers to a class.
{return} string the class name or the directory that this alias refers to
源码: framework/YiiBase.php#270 (显示)
public static function import($alias,$forceInclude=false)
{
    if(isset(
self::$_imports[$alias]))  // previously imported
        
return self::$_imports[$alias];

    if(
class_exists($alias,false) || interface_exists($alias,false))
        return 
self::$_imports[$alias]=$alias;

    if((
$pos=strrpos($alias,'\\'))!==false// a class name in PHP 5.3 namespace format
    
{
        
$namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
        if((
$path=self::getPathOfAlias($namespace))!==false)
        {
            
$classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
            if(
$forceInclude)
            {
                if(
is_file($classFile))
                    require(
$classFile);
                else
                    throw new 
CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
                
self::$_imports[$alias]=$alias;
            }
            else
                
self::$classMap[$alias]=$classFile;
            return 
$alias;
        }
        else
        {
            
// try to autoload the class with an autoloader
            
if (class_exists($alias,true))
                return 
self::$_imports[$alias]=$alias;
            else
                throw new 
CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
                    array(
'{alias}'=>$namespace)));
        }
    }

    if((
$pos=strrpos($alias,'.'))===false)  // a simple class name
    
{
        
// try to autoload the class with an autoloader if $forceInclude is true
        
if($forceInclude && (Yii::autoload($alias,true) || class_exists($alias,true)))
            
self::$_imports[$alias]=$alias;
        return 
$alias;
    }

    
$className=(string)substr($alias,$pos+1);
    
$isClass=$className!=='*';

    if(
$isClass && (class_exists($className,false) || interface_exists($className,false)))
        return 
self::$_imports[$alias]=$className;

    if((
$path=self::getPathOfAlias($alias))!==false)
    {
        if(
$isClass)
        {
            if(
$forceInclude)
            {
                if(
is_file($path.'.php'))
                    require(
$path.'.php');
                else
                    throw new 
CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
                
self::$_imports[$alias]=$className;
            }
            else
                
self::$classMap[$className]=$path.'.php';
            return 
$className;
        }
        else  
// a directory
        
{
            if(
self::$_includePaths===null)
            {
                
self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
                if((
$pos=array_search('.',self::$_includePaths,true))!==false)
                    unset(
self::$_includePaths[$pos]);
            }

            
array_unshift(self::$_includePaths,$path);

            if(
self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
                
self::$enableIncludePath=false;

            return 
self::$_imports[$alias]=$path;
        }
    }
    else
        throw new 
CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
            array(
'{alias}'=>$alias)));
}

Imports a class or a directory.

Importing a class is like including the corresponding class file. The main difference is that importing a class is much lighter because it only includes the class file when the class is referenced the first time.

Importing a directory is equivalent to adding a directory into the PHP include path. If multiple directories are imported, the directories imported later will take precedence in class file searching (i.e., they are added to the front of the PHP include path).

Path aliases are used to import a class or directory. For example,

  • application.components.GoogleMap: import the GoogleMap class.
  • application.components.*: import the components directory.


The same path alias can be imported multiple times, but only the first time is effective. Importing a directory does not import any of its subdirectories.

Starting from version 1.1.5, this method can also be used to import a class in namespace format (available for PHP 5.3 or above only). It is similar to importing a class in path alias format, except that the dot separator is replaced by the backslash separator. For example, importing application\components\GoogleMap is similar to importing application.components.GoogleMap. The difference is that the former class is using qualified name, while the latter unqualified.

Note, importing a class in namespace format requires that the namespace corresponds to a valid path alias once backslash characters are replaced with dot characters. For example, the namespace application\components must correspond to a valid path alias application.components.

log() 方法
public static void log(string $msg, string $level='info', string $category='application')
$msg string message to be logged
$level string level of the message (e.g. 'trace', 'warning', 'error'). It is case-insensitive.
$category string category of the message (e.g. 'system.web'). It is case-insensitive.
源码: framework/YiiBase.php#500 (显示)
public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
{
    if(
self::$_logger===null)
        
self::$_logger=new CLogger;
    if(
YII_DEBUG && YII_TRACE_LEVEL>&& $level!==CLogger::LEVEL_PROFILE)
    {
        
$traces=debug_backtrace();
        
$count=0;
        foreach(
$traces as $trace)
        {
            if(isset(
$trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
            {
                
$msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
                if(++
$count>=YII_TRACE_LEVEL)
                    break;
            }
        }
    }
    
self::$_logger->log($msg,$level,$category);
}

Logs a message. Messages logged by this method may be retrieved via CLogger::getLogs and may be recorded in different media, such as file, email, database, using CLogRouter.

powered() 方法
public static string powered()
{return} string a string that can be displayed on your Web page showing Powered-by-Yii information
源码: framework/YiiBase.php#584 (显示)
public static function powered()
{
    return 
Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
}

Returns a string that can be displayed on your Web page showing Powered-by-Yii information

registerAutoloader() 方法
public static void registerAutoloader(callback $callback, boolean $append=false)
$callback callback a valid PHP callback (function name or array($className,$methodName)).
$append boolean whether to append the new autoloader after the default Yii autoloader. Be careful using this option as it will disable autoloading via include path when set to true. After this the Yii autoloader can not rely on loading classes via simple include anymore and you have to import all classes explicitly.
源码: framework/YiiBase.php#661 (显示)
public static function registerAutoloader($callback$append=false)
{
    if(
$append)
    {
        
self::$enableIncludePath=false;
        
spl_autoload_register($callback);
    }
    else
    {
        
spl_autoload_unregister(array('YiiBase','autoload'));
        
spl_autoload_register($callback);
        
spl_autoload_register(array('YiiBase','autoload'));
    }
}

Registers a new class autoloader. The new autoloader will be placed before autoload and after any other existing autoloaders.

setApplication() 方法
public static void setApplication(CApplication $app)
$app CApplication the application instance. If this is null, the existing application singleton will be removed.
源码: framework/YiiBase.php#154 (显示)
public static function setApplication($app)
{
    if(
self::$_app===null || $app===null)
        
self::$_app=$app;
    else
        throw new 
CException(Yii::t('yii','Yii application can only be created once.'));
}

Stores the application instance in the class static member. This method helps implement a singleton pattern for CApplication. Repeated invocation of this method or the CApplication constructor will cause the throw of an exception. To retrieve the application instance, use app().

setLogger() 方法 (自版本 v1.1.8 可用)
public static void setLogger(CLogger $logger)
$logger CLogger the logger object.
源码: framework/YiiBase.php#575 (显示)
public static function setLogger($logger)
{
    
self::$_logger=$logger;
}

Sets the logger object.

setPathOfAlias() 方法
public static void setPathOfAlias(string $alias, string $path)
$alias string alias to the path
$path string the path corresponding to the alias. If this is null, the corresponding path alias will be removed.
源码: framework/YiiBase.php#391 (显示)
public static function setPathOfAlias($alias,$path)
{
    if(empty(
$path))
        unset(
self::$_aliases[$alias]);
    else
        
self::$_aliases[$alias]=rtrim($path,'\\/');
}

Create a path alias. Note, this method neither checks the existence of the path nor normalizes the path.

t() 方法
public static string t(string $category, string $message, array $params=array ( ), string $source=NULL, string $language=NULL)
$category string message category. Please use only word letters. Note, category 'yii' is reserved for Yii framework core code use. See CPhpMessageSource for more interpretation about message category.
$message string the original message
$params array parameters to be applied to the message using strtr. The first parameter can be a number without key. And in this case, the method will call CChoiceFormat::format to choose an appropriate message translation. Starting from version 1.1.6 you can pass parameter for CChoiceFormat::format or plural forms format without wrapping it with array. This parameter is then available as {n} in the message translation string.
$source string which message source application component to use. Defaults to null, meaning using 'coreMessages' for messages belonging to the 'yii' category and using 'messages' for the rest messages.
$language string the target language. If null (default), the application language will be used.
{return} string the translated message
源码: framework/YiiBase.php#613 (显示)
public static function t($category,$message,$params=array(),$source=null,$language=null)
{
    if(
self::$_app!==null)
    {
        if(
$source===null)
            
$source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
        if((
$source=self::$_app->getComponent($source))!==null)
            
$message=$source->translate($category,$message,$language);
    }
    if(
$params===array())
        return 
$message;
    if(!
is_array($params))
        
$params=array($params);
    if(isset(
$params[0])) // number choice
    
{
        if(
strpos($message,'|')!==false)
        {
            if(
strpos($message,'#')===false)
            {
                
$chunks=explode('|',$message);
                
$expressions=self::$_app->getLocale($language)->getPluralRules();
                if(
$n=min(count($chunks),count($expressions)))
                {
                    for(
$i=0;$i<$n;$i++)
                        
$chunks[$i]=$expressions[$i].'#'.$chunks[$i];

                    
$message=implode('|',$chunks);
                }
            }
            
$message=CChoiceFormat::format($message,$params[0]);
        }
        if(!isset(
$params['{n}']))
            
$params['{n}']=$params[0];
        unset(
$params[0]);
    }
    return 
$params!==array() ? strtr($message,$params) : $message;
}

Translates a message to the specified language. This method supports choice format (see CChoiceFormat), i.e., the message returned will be chosen from a few candidates according to the given number value. This feature is mainly used to solve plural format issue in case a message has different plural forms in some languages.

trace() 方法
public static void trace(string $msg, string $category='application')
$msg string message to be logged
$category string category of the message
源码: framework/YiiBase.php#485 (显示)
public static function trace($msg,$category='application')
{
    if(
YII_DEBUG)
        
self::log($msg,CLogger::LEVEL_TRACE,$category);
}

Writes a trace message. This method will only log a message when the application is in debug mode.

参见