YiiBase

Package system
Inheritance class YiiBase
Subclasses Yii
Since 1.0
Source Code 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.

Public Properties

Property Type Description Defined By
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

Public Methods

Method Description Defined By
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

Property Details

classMap property (available since 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 property (available since 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.

Method Details

app() method

public static CApplication app()
{return} CApplication the application singleton, null if the singleton has not been created yet.
Source Code: framework/YiiBase.php#132 (show)
public static function app()
{
    return 
self::$_app;
}

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

autoload() method

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
Source Code: framework/YiiBase.php#400 (show)
public static function autoload($className,$classMapOnly=false)
{
    
// 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() method

public static void beginProfile(string $token, string $category='application')
$token string token for the code block
$category string the category of this log message
Source Code: framework/YiiBase.php#511 (show)
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');

See Also

createApplication() method

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
Source Code: framework/YiiBase.php#123 (show)
public static function createApplication($class,$config=null)
{
    return new 
$class($config);
}

Creates an application of the specified class.

createComponent() method

public static mixed createComponent(mixed $config)
$config mixed the configuration. It can be either a string or an array.
{return} mixed the created object
Source Code: framework/YiiBase.php#180 (show)
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() method

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
Source Code: framework/YiiBase.php#111 (show)
public static function createConsoleApplication($config=null)
{
    return 
self::createApplication('CConsoleApplication',$config);
}

Creates a console application instance.

createWebApplication() method

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
Source Code: framework/YiiBase.php#96 (show)
public static function createWebApplication($config=null)
{
    return 
self::createApplication('CWebApplication',$config);
}

Creates a Web application instance.

endProfile() method

public static void endProfile(string $token, string $category='application')
$token string token for the code block
$category string the category of this log message
Source Code: framework/YiiBase.php#523 (show)
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.

See Also

getFrameworkPath() method

public static string getFrameworkPath()
{return} string the path of the framework
Source Code: framework/YiiBase.php#158 (show)
public static function getFrameworkPath()
{
    return 
YII_PATH;
}

getLogger() method

public static CLogger getLogger()
{return} CLogger message logger
Source Code: framework/YiiBase.php#531 (show)
public static function getLogger()
{
    if(
self::$_logger!==null)
        return 
self::$_logger;
    else
        return 
self::$_logger=new CLogger;
}

getPathOfAlias() method

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.
Source Code: framework/YiiBase.php#359 (show)
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() method

public static string getVersion()
{return} string the version of Yii framework
Source Code: framework/YiiBase.php#81 (show)
public static function getVersion()
{
    return 
'1.1.19';
}

import() method

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
Source Code: framework/YiiBase.php#263 (show)
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() method

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.
Source Code: framework/YiiBase.php#469 (show)
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() method

public static string powered()
{return} string a string that can be displayed on your Web page showing Powered-by-Yii information
Source Code: framework/YiiBase.php#553 (show)
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() method

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.
Source Code: framework/YiiBase.php#630 (show)
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() method

public static void setApplication(CApplication $app)
$app CApplication the application instance. If this is null, the existing application singleton will be removed.
Source Code: framework/YiiBase.php#147 (show)
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() method (available since v1.1.8)

public static void setLogger(CLogger $logger)
$logger CLogger the logger object.
Source Code: framework/YiiBase.php#544 (show)
public static function setLogger($logger)
{
    
self::$_logger=$logger;
}

Sets the logger object.

setPathOfAlias() method

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.
Source Code: framework/YiiBase.php#384 (show)
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() method

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
Source Code: framework/YiiBase.php#582 (show)
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.

See Also

trace() method

public static void trace(string $msg, string $category='application')
$msg string message to be logged
$category string category of the message
Source Code: framework/YiiBase.php#454 (show)
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.

See Also

© 2008–2017 by Yii Software LLC
Licensed under the three clause BSD license.
http://www.yiiframework.com/doc/api/1.1/YiiBase