Versions
Look up a class, method, property or event

CConsoleApplication

Package system.console
Inheritance class CConsoleApplication » CApplication » CModule » CComponent
Since 1.0
Source Code framework/console/CConsoleApplication.php
CConsoleApplication represents a console application.

CConsoleApplication extends CApplication by providing functionalities specific to console requests. In particular, it deals with console requests through a command-based approach:
  • A console application consists of one or several possible user commands;
  • Each user command is implemented as a class extending CConsoleCommand;
  • User specifies which command to run on the command line;
  • The command processes the user request with the specified parameters.


The command classes reside in the directory commandPath. The name of the class follows the pattern: <command-name>Command, and its file name is the same as the class name. For example, the 'ShellCommand' class defines a 'shell' command and the class file name is 'ShellCommand.php'.

To run the console application, enter the following on the command line:
php path/to/entry_script.php <command name> [param 1] [param 2] ...


You may use the following to see help instructions about a command:
php path/to/entry_script.php help <command name>

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
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
command CConsoleCommand|null Returns the currently running command. CConsoleApplication
commandMap array mapping from command name to command configurations. CConsoleApplication
commandPath string the directory that contains the command classes. CConsoleApplication
commandRunner CConsoleCommandRunner Returns the command runner. CConsoleApplication
components array Returns the application components. 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
homeUrl string the homepage URL CApplication
id string Returns the unique identifier for the application. CApplication
language string Returns the language that the user is using and the application should be targeted to. CApplication
locale an 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 the application name. CApplication
numberFormatter CNumberFormatter the locale-dependent number formatter. CApplication
params CAttributeCollection Returns user-defined parameters. CModule
parentModule CModule Returns the parent module. 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

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CApplication
__get() Getter magic method. CModule
__isset() Checks if a property value is null. 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. CConsoleApplication
displayException() Displays the uncaught PHP exception. CConsoleApplication
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
end() Terminates the application. 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
getCommand() Returns the currently running command. CConsoleApplication
getCommandPath() Returns the directory that contains the command classes. Defaults to 'protected/commands'. CConsoleApplication
getCommandRunner() Returns the command runner. CConsoleApplication
getComponent() Retrieves the named application component. CModule
getComponents() Returns the application components. 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
getGlobalState() Returns a global value. CApplication
getHomeUrl() Returns the homepage URL CApplication
getId() Returns the unique identifier for the application. 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() Retrieves the named application module. 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() Returns user-defined parameters. CModule
getParentModule() Returns the parent module. 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() Processes the user request. CConsoleApplication
raiseEvent() Raises an event. CComponent
run() Runs the application. 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
setCommand() This is shortcut method for CConsoleCommandRunner::setCommand(). CConsoleApplication
setCommandPath() Sets the directory that contains the command classes. CConsoleApplication
setComponent() Puts a component under the management of the module. CModule
setComponents() Sets the application components. 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() Sets the aliases that are used in the module. 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() Sets user-defined parameters. CModule
setRuntimePath() Sets the directory that stores runtime files. CApplication
setTimeZone() Sets the time zone used by this application. CApplication

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
createCommandRunner() Creates the command runner instance. CConsoleApplication
init() Initializes the application by creating the command runner. CConsoleApplication
initSystemHandlers() Initializes the error handlers. CApplication
preinit() Preinitializes the module. CModule
preloadComponents() Loads static application components. CModule
registerCoreComponents() Registers the core application components. CApplication

Events

Hide inherited events

EventDescriptionDefined By
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

Property Details

command property (available since v1.1.14)
public CConsoleCommand|null getCommand()
public void setCommand(CConsoleCommand $value)

Returns the currently running command. This is shortcut method for CConsoleCommandRunner::getCommand().

commandMap property
public array $commandMap;

mapping from command name to command configurations. Each command configuration can be either a string or an array. If the former, the string should be the file path of the command class. If the latter, the array must contain a 'class' element which specifies the command's class name or class path alias. The rest name-value pairs in the array are used to initialize the corresponding command properties. For example,

array(
  'email'=>array(
     'class'=>'path.to.Mailer',
     'interval'=>3600,
  ),
  'log'=>'path/to/LoggerCommand.php',
)

commandPath property
public string getCommandPath()
public void setCommandPath(string $value)

the directory that contains the command classes. Defaults to 'protected/commands'.

commandRunner property read-only

Returns the command runner.

Method Details

createCommandRunner() method
protected CConsoleCommandRunner createCommandRunner()
{return} CConsoleCommandRunner the command runner
Source Code: framework/console/CConsoleApplication.php#101 (show)
protected function createCommandRunner()
{
    return new 
CConsoleCommandRunner;
}

Creates the command runner instance.

displayError() method
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
Source Code: framework/console/CConsoleApplication.php#115 (show)
public function displayError($code,$message,$file,$line)
{
    echo 
"PHP Error[$code]: $message\n";
    echo 
"    in file $file at line $line\n";
    
$trace=debug_backtrace();
    
// skip the first 4 stacks as they do not tell the error position
    
if(count($trace)>4)
        
$trace=array_slice($trace,4);
    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";
    }
}

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

displayException() method
public void displayException(Exception $exception)
$exception Exception the uncaught exception
Source Code: framework/console/CConsoleApplication.php#144 (show)
public function displayException($exception)
{
    echo 
$exception;
}

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

getCommand() method (available since v1.1.14)
public CConsoleCommand|null getCommand()
{return} CConsoleCommand|null the currently active command.
Source Code: framework/console/CConsoleApplication.php#186 (show)
public function getCommand()
{
    return 
$this->getCommandRunner()->getCommand();
}

Returns the currently running command. This is shortcut method for CConsoleCommandRunner::getCommand().

getCommandPath() method
public string getCommandPath()
{return} string the directory that contains the command classes. Defaults to 'protected/commands'.
Source Code: framework/console/CConsoleApplication.php#152 (show)
public function getCommandPath()
{
    
$applicationCommandPath $this->getBasePath().DIRECTORY_SEPARATOR.'commands';
    if(
$this->_commandPath===null && file_exists($applicationCommandPath))
        
$this->setCommandPath($applicationCommandPath);
    return 
$this->_commandPath;
}

getCommandRunner() method
public CConsoleCommandRunner getCommandRunner()
{return} CConsoleCommandRunner the command runner.
Source Code: framework/console/CConsoleApplication.php#175 (show)
public function getCommandRunner()
{
    return 
$this->_runner;
}

Returns the command runner.

init() method
protected void init()
Source Code: framework/console/CConsoleApplication.php#75 (show)
protected function init()
{
    
parent::init();
    if(empty(
$_SERVER['argv']))
        die(
'This script must be run from the command line.');
    
$this->_runner=$this->createCommandRunner();
    
$this->_runner->commands=$this->commandMap;
    
$this->_runner->addCommands($this->getCommandPath());
}

Initializes the application by creating the command runner.

processRequest() method
public void processRequest()
Source Code: framework/console/CConsoleApplication.php#90 (show)
public function processRequest()
{
    
$exitCode=$this->_runner->run($_SERVER['argv']);
    if(
is_int($exitCode))
        
$this->end($exitCode);
}

Processes the user request. This method uses a console command runner to handle the particular user command. Since version 1.1.11 this method will exit application with an exit code if one is returned by the user command.

setCommand() method (available since v1.1.14)
public void setCommand(CConsoleCommand $value)
$value CConsoleCommand the currently active command.
Source Code: framework/console/CConsoleApplication.php#196 (show)
public function setCommand($value)
{
    
$this->getCommandRunner()->setCommand($value);
}

This is shortcut method for CConsoleCommandRunner::setCommand().

setCommandPath() method
public void setCommandPath(string $value)
$value string the directory that contains the command classes.
Source Code: framework/console/CConsoleApplication.php#164 (show)
public function setCommandPath($value)
{
    if((
$this->_commandPath=realpath($value))===false || !is_dir($this->_commandPath))
        throw new 
CException(Yii::t('yii','The command path "{path}" is not a valid directory.',
            array(
'{path}'=>$value)));
}

Total 1 comment

#572 report it
Morgan at 2010/04/20 02:58pm
commandPath Example

If you need to modify the commandPath, put something like the following into protected/config/main.php or console.php:

    'commandPath' => dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'commands'.DIRECTORY_SEPARATOR.'shell',

This would add all commands from the protected/commands/shell directory. The value needs to be something that the PHP realpath() function will accept and must be a directory that exists.

Leave a comment

Please to leave your comment.