Home > Backend Development > PHP Tutorial > Yii Framework Official Guide Series 50 - Special Topic: Console Applications

Yii Framework Official Guide Series 50 - Special Topic: Console Applications

黄舟
Release: 2023-03-05 19:10:02
Original
1494 people have browsed it



The console application is mainly used to implement offline operations required for online web applications, such as code generation, search index compilation, email sending, etc. The Yii framework provides a framework for writing console applications in an object-oriented manner. It allows console applications to access resources used by online web applications (such as database connection information).

1. Overview

Yii can run each console task in the command line. The console command is a class inherited from CConsoleCommand.

When we use the yiic webapp tool to create an initialized Yii application skeleton, we can see the following two files in the protected folder:

  • yiic: This is an executable script running on Linux/Unix;

  • yiic.bat: This is an executable batch script running on Windows.

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

cd protected
yiic help
Copy after login

This will display a series of console commands. By default, these valid commands include those provided by the Yii framework (system commands) and those written by developers themselves for stand-alone applications (user commands).

Yii Framework Official Guide Series 50 - Special Topic: Console Applications

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

yiic help <command-name></command-name>
Copy after login

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

yiic <command-name> [parameters...]</command-name>
Copy after login

2. Create a command

The console command is saved in the form of a class file under a path such as CConsoleApplication::command. By default, it points to the folder protected/commands.

a The console command class must inherit from CConsoleCommand. The class name must be in the format XyzCommand, where Xyz represents the command name with the first letter capitalized. 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 obtain commands named in different forms and stored in different folders. Class.

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

When executing a console command, the CConsoleCommand::run() method will be called by the console application. All console parameters will also be passed into this method in the form of the following method fragment:


public function run($args) { ... }
Copy after login

where $args represents the command Additional parameters given by line.

In the console command, we can use Yii::app() to access the console application instance. Not only that, 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 usage in web applications.

Info: Starting from version 1.1.1, we can also create global commands shared by all Yii applications on the same machine: define an environment variable named YII_CONSOLE_COMMANDS Point to an existing folder, and then place our global command class under this folder.

3. Console command action

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

A console command often needs to process different command line parameters, some are required and some are optional. The console command also needs to provide some subcommands to handle different subtasks. These tasks can be simplified using console command actions.

A console command action is a method in the console command class. The method name must be in the format actionXyz, where Xyz represents the action name with the first letter capitalized. For example, an actionIndex method defines an action named index action.

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

yiic <command-name> <action-name> --option1=value1 --option2=value2 ...</action-name></command-name>
Copy after login

Additional option-value pairs will be passed into the action method as named parameters. . The value of an xyz operation will be passed to the action method in the form of the $xyz parameter. For example, if we define the following command class:


class SitemapCommand extends CConsoleCommand
{
    public function actionIndex($type, $limit=5) { ... }
    public function actionInit() { ... }
}
Copy after login

Then, the following console command calls actionIndex( 'News', 5) will have results:

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
Copy after login

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

Note: does not support the optional parameter format --type News, -t News.

A parameter value can be an array (must Array type hint required):


public function actionIndex(array $types) { ... }
Copy after login

If you want to use an array value in a command line parameter, simply repeat The same option:

yiic sitemap index --types=News --types=Article
Copy after login

The above command will eventually call actionIndex(array('News', 'Article')).

Starting from version 1.1.6, Yii also supports the use of anonymous Action parameters and global options.

匿名参数表示这些命令行参数不是以选项的形式呈现. 例如, 在命令 yiic sitemap index --limit=5 News中, 我们有一个值为News的匿名参数和命名参数 limit,其值为5。

为了使用匿名参数, 一个命令动作必须声明参数为 $args的形式. 例如,


public function actionIndex($limit=10, $args=array()) {...}
Copy after login

$args数组将会装入所有的匿名参数值.

全局选项代表那些命令行选项可以被一个命令中所有动作共享的选项. 例如, 在一个命令中提供了多个选项, 我们可能想要每一个动作识别一个名为verbose的动作. 当然我们可以在每一个动作方法中声明 $verbose 参数, 一个更好的方式是将其声明为这个命令类的公有成员变量, 将 verbose 转换为全局参数:


class SitemapCommand extends CConsoleCommand
{
    public $verbose=false;
    public function actionIndex($type) {...}
}
Copy after login

上面的代码允许我们执行一个带 verbose 选项的命令:

yiic sitemap index --verbose=1 --type=News
Copy after login

4. 退出代码

Note: 在控制台命令中退出代码的特性从版本 1.1.11起有效.

通过cronjob或者使用一个持续集成的服务器自动运行控制台命令的时候, 要么命令运行运行成功,要么命令运行失败. 这可以通过检查进程返回的退出代码来查看。

这些退出码是从0-254的整型值(this is the range in php world), 其中 0 表示退出成功其他的所有非0值表示出现了错误.

在一个动作方法或者控制台命令的 run() 方法中你可以在退出时返回整型值退出码 ,例如:


if (/* error */) {
    return 1; // exit with error code 1
}
// ... do something ...
return 0; // exit successfully
Copy after login

如果没有返回值, 应用将会退出返回 0.

5. 自定义控制台应用

默认情况下, 如果一个应用是使用yiic webapp工具创建的, 命令行应用的配置将会放在 protected/config/console.php文件中. 和一个Web应用配置文件一样, 这个文件是一个返回控制台应用实例的初始化配置值的数组的PHP脚本。所以CConsoleApplication的任何公有属性都可以在该文件中配置.

因为控制台命令经常被创建来服务于Web应用, 所以需要访问资源(如数据库连接)。我们可以在控制台配置文件中以如下方式来实现 :


return array(
    ......
    'components'=>array(
        'db'=>array(
            ......
        ),
    ),
);
Copy after login

正如我们所看到的那样, 配置的格式和我们在Web应用中的配置类似.这是因为CConsoleApplication和 CWebApplication 的基类相同。

 以上就是Yii框架官方指南系列50——专题:控制台应用的内容,更多相关内容请关注PHP中文网(www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template