---
title: "扩展 Yii Framework 的控制台功能"
author: "zhex"
date: "2009-10-16T06:45:40Z"
tags: []
slug: "yii-framework"
draft: false
lastmod: "2009-10-16T06:45:40Z"
id: 491939
url: "https://zhex.iteye.com/blog/491939"
---

Yii已经为我们提供了很好的控制台功能，我们可以利用控制台创建webapp，controller， action等来加速我们的开发。同时我们还可以自己来扩展控制台应用（console application）来满足我们更多的项目需求。

console app 和 web app 类似，我们需要一个入口文件，默认的情况我们可以在protected目录发现这些文件（yiic.php， yiic， yiic.bat）， 其中yiic.php为入口文件，yiic为linux的执行文件，yiic.bat为windows上的执行文件。这3个文件会在我们创建webapp的时候自动生成， 如果没有我们也可以手动加入这3个文件。


```php

<?php
//yiic.php

// change the following paths if necessary
$yiic=dirname(__FILE__).'/../framework/yiic.php';
$config=dirname(__FILE__).'/config/console.php';

require_once($yiic);


```


要扩展控制台命令，我们需要写一个xxxCommand类来继承CConsoleCommand，并存放在protected/commands 目录下。 然后通过默认配置文件 protected/config/console.php 来配置console app


```php

<?php
//console.php

// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'My Console Application',
);

```


现在让我们来写一个简单的控制台命令TestCommand，要求输入命令（test）和用户名（username），然后在屏幕上打印出 hello username.

```php

<?php
class TestCommand extends CConsoleCommand {
    
    public function getHelp() {
        return 'test command help';
    }
    
    public function run($args) {
        echo 'hello '. $arg[0];
    }
}
?>

```


在这个类中我们需要完成2个方法，一个是getHelp()，他用于提供Test这个类命令的帮助信息，我们可以在shell中通过命令：yiic help test 来查看这个类的帮助。
此外这个类的主要功能是通过继承 run($args) 这个方法来实现的，其中$args 为从命令行获得参数数组。
现在如果我们在屏幕上输入：yiic test zhex
我们将看到程序返回： hello zhex

在console app中我们还可以实现很多有用的功能，比如发送Email， 数据库更新等。也许通过你的才智，还能写出更多有趣的功能。