Yii Framework Official Guide Series 50--topic: Console Applications

Source: Internet
Author: User
Tags yii



Console applications are primarily used to implement offline operations required for online Web applications, such as code generation, search index compilation, mail sending, and so on. The YII Framework provides a framework for writing console applications in an object-oriented manner. It allows the console app to access the resources (such as database connection information) used by the online web app.

1. Overview

Yii can run each console task as a command line, and the console command is a class that inherits from Cconsolecommand.

When we use the YIIC WebApp tool to create an initialized Yii application skeleton, we can see the following two files under the protected folder:

    • YIIC: This is an executable script running on the Linux/unix;

    • Yiic.bat: This is an executable batch script that runs on Windows.

In the console window, we can enter the following command:

CD PROTECTEDYIIC Help

This will display a series of console commands. By default, these are valid commands that are provided by the YII framework (System commands) and developed by the developer themselves (user commands) for standalone applications.

If you want to see how to use a command, you can use:

YIIC Help <command-name>

To execute a command, you can use the following command format:

YIIC <command-name> [Parameters ...]

2. Create a command

The console commands are saved as a class file in the form of a cconsoleapplication::command path. By default, point to Folder Protected/commands.

One console command class must inherit from Cconsolecommand. This class name must be in the Xyzcommand format, where Xyz represents the first uppercase command name. For example, a sitemap command must use the class name Sitemapcommand. Console command names are case-sensitive.

Tip: by configuring Cconsoleapplication::command matching, you can get command classes that are named in different forms and stored under different folders.

In order to create a new command, you often need to rewrite cconsolecommand::run () or develop one or more command actions.

When a console command is executed, the Cconsolecommand::run () method is invoked by the console application. All console parameters are also passed into this method as a fragment of the following method:


Public function Run ($args) {...}

Where $args represents the extra parameters given by the command line.

In console commands, we can use Yii::app () to access the console application instance, and we can also access resources such as database connections (e.g. Yii::app ()->db). You can see that this usage is very similar to the use in Web apps.

Info: starting with version 1.1.1, we can also create global commands shared by all YII apps on the same machine: Define an environment variable named Yii_console_commands to an existing folder, Then put our global command class in this folder.

3. Console command Action (action)

Note: this console command action feature is valid from version 1.1.5.

A console command often needs to handle different command-line arguments, some of which are necessary, and some are optional. The console command also needs to provide some sub-commands to handle different sub-tasks. These efforts can simplify the use of console command actions.

A console command action is a method in a console command class. This method name must be in the ACTIONXYZ format, where XYZ represents the first uppercase action name. For example, a Actionindex method defines an action named index.

To perform a specific action, we can use the following command-line format:

YIIC <command-name> <action-name>--option1=value1--option2=value2 ...

The extra Option-value pair will be passed in to the action method as a named parameter. The value of an XYZ operation is passed into the action method as a $xyz parameter. For example, if we define the following command class:


Class Sitemapcommand extends cconsolecommand{public    function Actionindex ($type, $limit =5) {...}    Public Function Actioninit () {...}}

The following console command will then have the result when calling Actionindex (' News ', 5):

YIIC Sitemap Index--type=news--limit=5//$limit takes default VALUEYIIC sitemap index--type=news//$limit takes default value//because ' index ' is a default action, we can omit the action NAMEYIIC Sitemap--type=news//The order of options D OES not MATTERYIIC sitemap index--limit=5--type=news

If an operation does not specify a value (e.g.--type instead of--type=news), the corresponding action parameter value is assumed to be true.

Note: optional parameter formats are not supported--type news,-T news.

A parameter value can be an array (you must have an array type hint):


Public function Actionindex (array $types) {...}

To use array values in command-line arguments, simply repeat the same option:

YIIC Sitemap Index--types=news--types=article

The above command will eventually call Actionindex (Array (' News ', ' article ')).

Starting with version 1.1.6, YII also supports the use of anonymous action parameters and global options.

Anonymous parameters indicate that these command-line arguments are not rendered as options. For example, in the command YIIC sitemap Index--limit=5 News, we have an anonymous parameter with a value of news and a named parameter limit with a value of 5.

In order to use anonymous parameters, a command action must declare the parameter to be $args form. For example


Public Function Actionindex ($limit =10, $args =array ()) {...}

$args array will load all the anonymous parameter values.

Global options represent options that command-line options can be shared by all actions in a command. For example, in a command that provides multiple options, we may want each action to recognize an action called verbose. Of course we can declare $verbose parameters in each action method, a better way is to declare it as a public member variable of this command class, and convert verbose to global parameters:


Class Sitemapcommand extends cconsolecommand{public    $verbose =false;    Public Function Actionindex ($type) {...}}

The above code allows us to execute a command with the verbose option:

YIIC Sitemap Index--verbose=1--type=news

4. Exit code

Note: the feature that exits the code in the console command is valid from version 1.1.11.

When a console command is run automatically through cronjob or with a server that is continuously integrated, either the command runs successfully or the command fails. This can be viewed by checking the exit code returned by the process.

These exit codes are integer values from 0-254 (this is the range in PHP World), where 0 indicates that all other non-0 values that exited successfully indicate an error.

In the Run () method of an action method or console command, you can return an integer value exit code on exit, for example:


if (/* ERROR */) {    return 1;//exit with error code 1}//... "Do something ... return 0;//exit successfully

If there is no return value, the app exits returning 0.

5. Customizing the console App

By default, if an app was created using the YIIC webapp tool, the command line app's configuration will be placed in the protected/config/console.php file. As with a Web application configuration file, this file is a PHP script that returns an array of initialization configuration values for the console application instance. Therefore, any public properties of Cconsoleapplication can be configured in this file.

Because console commands are often created to serve Web applications, you need access to resources such as database connections. We can do this in the console configuration file as follows:


Return Array (...    ') Components ' =>array (        ' db ' =>array (...        ),    ),);

As we can see, the configured format is similar to our configuration in a Web app. This is because Cconsoleapplication and cwebapplication have the same base class.

The above is the Yii Framework Official Guide Series 50--topic: The content of the console application, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.