0 follower

YiiBase

Package system
Inheritance class YiiBase
Subclasses Yii
Since 1.0
Version $Id$
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 Methods

Hide inherited methods

MethodDescriptionDefined By
app() YiiBase
autoload() Class autoload loader. YiiBase
beginProfile() Marks the begin 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 the definition of a class or a directory of class files. YiiBase
log() Logs a message. YiiBase
powered() YiiBase
registerAutoloader() Registers a new class autoloader. YiiBase
setApplication() Stores the application instance in the class static member. YiiBase
setPathOfAlias() Create a path alias. YiiBase
t() Translates a message to the specified language. YiiBase
trace() Writes a trace message. YiiBase

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#114 (show)
public static function app()
{
    return 
self::$_app;
}

autoload() method
public static boolean autoload(string $className)
$className string class name
{return} boolean whether the class has been loaded successfully
Source Code: framework/YiiBase.php#329 (show)
public static function autoload($className)
{
    
// use include so that the error PHP file may appear
    
if(isset(self::$_coreClasses[$className]))
        include(
YII_PATH.self::$_coreClasses[$className]);
    else if(isset(
self::$_classes[$className]))
        include(
self::$_classes[$className]);
    else
    {
        include(
$className.'.php');
        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#414 (show)
public static function beginProfile($token,$category='application')
{
    
self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
}

Marks the begin 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 (available since v1.0.10)
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#106 (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#164 (show)
public static function createComponent($config)
{
    if(
is_string($config))
    {
        
$type=$config;
        
$config=array();
    }
    else if(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)
    {
        
$args=func_get_args();
        if(
$n===2)
            
$object=new $type($args[1]);
        else if(
$n===3)
            
$object=new $type($args[1],$args[2]);
        else if(
$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 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.

NOTE: the array-typed configuration has been supported since version 1.0.1.

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

Creates a console application instance.

createWebApplication() method
public static void 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'.
Source Code: framework/YiiBase.php#79 (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#426 (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#140 (show)
public static function getFrameworkPath()
{
    return 
YII_PATH;
}

getLogger() method
public static CLogger getLogger()
{return} CLogger message logger
Source Code: framework/YiiBase.php#434 (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#290 (show)
public static function getPathOfAlias($alias)
{
    if(isset(
self::$_aliases[$alias]))
        return 
self::$_aliases[$alias];
    else if((
$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);
        else if(
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#65 (show)
public static function getVersion()
{
    return 
'1.0.12';
}

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.
{return} string the class name or the directory that this alias refers to
Source Code: framework/YiiBase.php#229 (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(isset(
self::$_coreClasses[$alias]) || ($pos=strrpos($alias,'.'))===false)  // a simple class name
    
{
        
self::$_imports[$alias]=$alias;
        if(
$forceInclude)
        {
            if(isset(
self::$_coreClasses[$alias])) // a core class
                
require(YII_PATH.self::$_coreClasses[$alias]);
            else
                require(
$alias.'.php');
        }
        return 
$alias;
    }

    if((
$className=(string)substr($alias,$pos+1))!=='*' && (class_exists($className,false) || interface_exists($className,false)))
        return 
self::$_imports[$alias]=$className;

    if((
$path=self::getPathOfAlias($alias))!==false)
    {
        if(
$className!=='*')
        {
            
self::$_imports[$alias]=$className;
            if(
$forceInclude)
                require(
$path.'.php');
            else
                
self::$_classes[$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(
set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
                throw new 
CException(Yii::t('yii','Unable to import "{alias}". Please check your server configuration to make sure you are allowed to change PHP include_path.',array('{alias}'=>$alias)));
            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 the definition of a class or a directory of class files.

Path aliases are used to refer to the class file or directory being imported. If importing a path alias ending with '.*', the alias is considered as a directory which will be added to the PHP include paths; Otherwise, the alias is translated to the path of a class file which is included when needed.

For example, importing 'system.web.*' will add the 'web' directory of the framework to the PHP include paths; while importing 'system.web.CController' will include the class file 'web/CController.php' when needed.

The same alias can be imported multiple times, but only the first time is effective.

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#386 (show)
public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
{
    if(
self::$_logger===null)
        
self::$_logger=new CLogger;
    
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#445 (show)
public static function powered()
{
    return 
'Powered by <a href="https://www.yiiframework.com/" target="_blank">Yii Framework</a>.';
}

registerAutoloader() method (available since v1.0.10)
public static void registerAutoloader(callback $callback)
$callback callback a valid PHP callback (function name or array($className,$methodName)).
Source Code: framework/YiiBase.php#498 (show)
public static function registerAutoloader($callback)
{
    
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#129 (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().

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#315 (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. Starting from version 1.0.2, 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.
$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. This parameter has been available since version 1.0.3.
{return} string the translated message
Source Code: framework/YiiBase.php#472 (show)
public static function t($category,$message,$params=array(),$source=null,$language=null)
{
    if(
self::$_app!==null)
    {
        if(
$source===null)
            
$source=$category==='yii'?'coreMessages':'messages';
        if((
$source=self::$_app->getComponent($source))!==null)
            
$message=$source->translate($category,$message,$language);
    }
    if(
$params===array())
        return 
$message;
    if(isset(
$params[0])) // number choice
    
{
        
$message=CChoiceFormat::format($message,$params[0]);
        unset(
$params[0]);
    }
    return 
$params!==array() ? strtr($message,$params) : $message;
}

Translates a message to the specified language. Starting from version 1.0.2, 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#351 (show)
public static function trace($msg,$category='application')
{
    if(
YII_DEBUG)
    {
        if(
YII_TRACE_LEVEL>0)
        {
            
$traces=debug_backtrace();
            
$count=0;
            foreach(
$traces as $trace)
            {
                if(isset(
$trace['file'],$trace['line']))
                {
                    
$className=substr(basename($trace['file']),0,-4);
                    if(!isset(
self::$_coreClasses[$className]) && $className!=='YiiBase')
                    {
                        
$msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
                        if(++
$count>=YII_TRACE_LEVEL)
                            break;
                    }
                }
            }
        }
        
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