Console Applications
Console applications are mainly used to perform offline work needed by anonline Web application, such as code generation, search index compiling, emailsending, etc. Yii provides a framework for writing console applications inan object-oriented way. It allows a console application to accessthe resources (e.g. DB connections) that are used by an online Web application.
1. Overview
Yii represents each console task in terms of a command.A console command is written as a class extending from CConsoleCommand.
When we use the yiic webapp
tool to create an initial skeleton Yii application,we may find two files under the protected
directory:
- yiic: this is an executable script used on Linux/Unix;
- yiic.bat: this is an executable batch file used on Windows.
In a console window, we can enter the following commands:
- cd protected
- yiic help
This will display a list of available console commands. By default, the availablecommands include those provided by Yii framework (called system commands)and those developed by users for individual applications (called user commands).
To see how to use a command, we can execute
- yiic help <command-name>
And to execute a command, we can use the following command format:
- yiic <command-name> [parameters...]
2. Creating Commands
Console commands are stored as class files under the directory specified byCConsoleApplication::commandPath. By default, this refers to the directoryprotected/commands
.
A console command class must extend from CConsoleCommand. The class namemust be of format XyzCommand
, where Xyz
refers to the command name withthe first letter in upper case. For example, a sitemap
command must usethe class name SitemapCommand
. Console command names are case-sensitive.
Tip: By configuring CConsoleApplication::commandMap, one can also have command classes in different naming conventions and located in different directories.
To create a new command, one often needs to override CConsoleCommand::run()or develop one or several command actions (to be explained in the next section).
When executing a console command, the CConsoleCommand::run() method will beinvoked by the console application. Any console command parameters will be passedto the method as well, according to the following signature of the method:
- public function run($args) { ... }
where $args
refers to the extra parameters given in the command line.
Within a console command, we can use Yii::app()
to access the console applicationinstance, through which we can also access resources such as database connections(e.g. Yii::app()->db
). As we can tell, the usage is very similar to what we cando in a Web application.
Info: Starting from version 1.1.1, we can also create global commands that are shared by all Yii applications on the same machine. To do so, define an environment variable namedYII_CONSOLE_COMMANDS
which should point to an existing directory. We can then put our global command class files under this directory.
3. Console Command Action
Note: The feature of console command action has been available since version 1.1.5.
A console command often needs to handle different command line parameters, some required,some optional. A console command may also need to provide several sub-commands to handledifferent sub-tasks. These work can be simplified using console command actions.
A console command action is a method in a console command class.The method name must be of the format actionXyz
, where Xyz
refers to the actionname with the first letter in upper-case. For example, a method actionIndex
definesan action named index
.
To execute a specific action, we use the following console command format:
- yiic <command-name> <action-name> --option1=value1 --option2=value2 ...
The additional option-value pairs will be passed as named parameters to the action method.The value of a xyz
option will be passed as the $xyz
parameter of the action method.For example, if we define the following command class:
- class SitemapCommand extends CConsoleCommand
- {
- public function actionIndex($type, $limit=5) { ... }
- public function actionInit() { ... }
- }
Then, the following console commands will all result in calling actionIndex('News', 5)
:
- yiic sitemap index --type=News --limit=5
- // $limit takes default value
- yiic sitemap index --type=News
- // $limit takes default value
- // because 'index' is a default action, we can omit the action name
- yiic sitemap --type=News
- // the order of options does not matter
- yiic sitemap index --limit=5 --type=News
If an option is given without value (e.g. —type
instead of —type=News
), the correspondingaction parameter value will be assumed to be boolean true
.
Note: We do not support alternative option formats such as—type News
,-t News
.
A parameter can take an array value by declaring it with array type hinting:
- public function actionIndex(array $types) { ... }
To supply the array value, we simply repeat the same option in the command line as needed:
- yiic sitemap index --types=News --types=Article
The above command will call actionIndex(array('News', 'Article'))
ultimately.
Starting from version 1.1.6, Yii also supports using anonymous action parameters and global options.
Anonymous parameters refer to those command line parameters not in the format of options.For example, in a command yiic sitemap index —limit=5 News
, we have an anonymous parameter whose valueis News
while the named parameter limit
is taking the value 5.
To use anonymous parameters, a command action must declare a parameter named as $args
. For example,
- public function actionIndex($limit=10, $args=array()) {...}
The $args
array will hold all available anonymous parameter values.
Global options refer to those command line options that are shared by all actions in a command.For example, in a command that provides several actions, we may want every action to recognizean option named as verbose
. While we can declare $verbose
parameter in every action method,a better way is to declare it as a public member variable of the command class, which turns verbose
into a global option:
- class SitemapCommand extends CConsoleCommand
- {
- public $verbose=false;
- public function actionIndex($type) {...}
- }
The above code will allow us to execute a command with a verbose
option:
- yiic sitemap index --verbose=1 --type=News
4. Exit Codes
Note: The possibility to return exit codes in console commands has been available since version 1.1.11.
When running console commands automatically, via cronjob or using a continuous integration server, it isalways interesting if the command ran successfully or if there were errors.This can be done by checking the exit code a process returns on exit.
These codes are integer values between 0 and 254 (this is the range in php world),where 0 should be returned on success and all other values greater than 0 will indicate an error.
In an action method or in the run()
method of your console command you can return an integer valueto exit your application with an exit code.Example:
- if (/* error */) {
- return 1; // exit with error code 1
- }
- // ... do something ...
- return 0; // exit successfully
When there is no return value, application will exit with code 0.
5. Customizing Console Applications
By default, if an application is created using the yiic webapp
tool, the configurationfor the console application will be protected/config/console.php
. Like a Web applicationconfiguration file, this file is a PHP script which returns an array representing theproperty initial values for a console application instance. As a result, any public propertyof CConsoleApplication can be configured in this file.
Because console commands are often created to serve for the Web application, they needto access the resources (such as DB connections) that are used by the latter. We can do soin the console application configuration file like the following:
- return array(
- ......
- 'components'=>array(
- 'db'=>array(
- ......
- ),
- ),
- );
As we can see, the format of the configuration is very similar to what we do ina Web application configuration. This is because both CConsoleApplication and CWebApplicationshare the same base class.
原文: https://www.yiiframework.com/doc/guide/1.1/zh-cn/topics.console