Table of Contents
1. Overview
2. Create a command
3. Console command action
4. 退出代码
5. 自定义控制台应用
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

Feb 16, 2017 am 09:53 AM



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)!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

RESTful API development in Yii framework RESTful API development in Yii framework Jun 21, 2023 pm 12:34 PM

Yii is a high-performance MVC framework based on PHP. It provides a very rich set of tools and functions to support the rapid and efficient development of web applications. Among them, the RESTful API function of the Yii framework has attracted more and more attention and love from developers, because using the Yii framework can easily build high-performance and easily scalable RESTful interfaces, providing strong support for the development of web applications. . Introduction to RESTfulAPI RESTfulAPI is a

Yii framework middleware: providing multiple data storage support for applications Yii framework middleware: providing multiple data storage support for applications Jul 28, 2023 pm 12:43 PM

Yii framework middleware: providing multiple data storage support for applications Introduction Middleware (middleware) is an important concept in the Yii framework, which provides multiple data storage support for applications. Middleware acts like a filter, inserting custom code between an application's requests and responses. Through middleware, we can process, verify, filter requests, and then pass the processed results to the next middleware or final handler. Middleware in the Yii framework is very easy to use

How to use Yii framework in PHP How to use Yii framework in PHP Jun 27, 2023 pm 07:00 PM

With the rapid development of web applications, modern web development has become an important skill. Many frameworks and tools are available for developing efficient web applications, among which the Yii framework is a very popular framework. Yii is a high-performance, component-based PHP framework that uses the latest design patterns and technologies, provides powerful tools and components, and is ideal for building complex web applications. In this article, we will discuss how to use Yii framework to build web applications. Install Yii framework first,

Steps to implement web page caching and page chunking using Yii framework Steps to implement web page caching and page chunking using Yii framework Jul 30, 2023 am 09:22 AM

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

Create a game guide website using Yii framework Create a game guide website using Yii framework Jun 21, 2023 pm 01:45 PM

In recent years, with the rapid development of the game industry, more and more players have begun to look for game strategies to help them pass the game. Therefore, creating a game guide website can make it easier for players to obtain game guides, and at the same time, it can also provide players with a better gaming experience. When creating such a website, we can use the Yii framework for development. The Yii framework is a web application development framework based on the PHP programming language. It has the characteristics of high efficiency, security, and strong scalability, and can help us create a game guide more quickly and efficiently.

Yii Framework Middleware: Add logging and debugging capabilities to your application Yii Framework Middleware: Add logging and debugging capabilities to your application Jul 28, 2023 pm 08:49 PM

Yii framework middleware: Add logging and debugging capabilities to applications [Introduction] When developing web applications, we usually need to add some additional features to improve the performance and stability of the application. The Yii framework provides the concept of middleware that enables us to perform some additional tasks before and after the application handles the request. This article will introduce how to use the middleware function of the Yii framework to implement logging and debugging functions. [What is middleware] Middleware refers to the processing of requests and responses before and after the application processes the request.

How to use controllers to handle Ajax requests in the Yii framework How to use controllers to handle Ajax requests in the Yii framework Jul 28, 2023 pm 07:37 PM

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework

Debugging Tools in the Yii Framework: Profiling and Debugging Applications Debugging Tools in the Yii Framework: Profiling and Debugging Applications Jun 21, 2023 pm 06:18 PM

In modern web application development, debugging tools are indispensable. They help developers find and solve various problems with their applications. As a popular web application framework, the Yii framework naturally provides some debugging tools. This article will focus on the debugging tools in the Yii framework and discuss how they help us analyze and debug applications. GiiGii is a code generator for the Yii framework. It can automatically generate code for Yii applications, such as models, controllers, views, etc. Using Gii,

See all articles