yii framework中,在application中使用console。

yii框架 在现有的application中使用console:

假设目录结构为

application/constrollers
application/models
application/extensions
application/views
application/commponents
...

 

1 在application文件夹下,新建yiic

代码为:

#!/usr/bin/env php
<?php

require_once(dirname(__FILE__).'/yiic.php'); // 当前目录下有yiic.php,步骤2用到

 

2 在application文件夹下,新建yiic.php

代码为:

<?php

// change the following paths if necessary
$yiic=dirname(__FILE__).'/../../yii/framework/yiic.php'; // 指向yii框架核心的yiic.php文件夹。
$config=dirname(__FILE__).'/config/console.php'; // 配置文件 步骤3要用
require_once($yiic);

 

3 在application文件夹下,创建console.php

4 配置文件,代码

array(
# base config
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
'name' => 'hello world',
);

配置好后,执行./yiic,这个时候出现下列文字。代表yiic的基本环境配置成功。

 

5 丰富配置,加入console要用到的db,components配置

array(
        # base config
        'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
        'name' => 'kqw',
        
        #  import config
        'import' => [
            'application.models.*',
            'application.components.*',
        ],
        # db config
        'components' => [
            'db' => array(
                'connectionString' => 'mysql:host=127.0.0.1;dbname=kqw',
                'emulatePrepare' => true,
                'username' => 'kqw',
                'password' => '123456',
                'charset' => 'utf8',
            ),
        ],
    );

6 在application创建commands文件夹。写一份测试样例代码,新建TestCommand.php

<?php

class TestCommand extends CConsoleCommand {
    public function actionIndex() {
        echo 'hello world', "\n";
    }
    public function actionDemo() {
        $user = User::model()->findByPK(1);
        echo $user->username, "\n";
    }
}

7 在application下,执行./yiic Test index即可

PS:中间有用5.4语法,短数组。类似$array = [1, 2, 3];

posted @ 2014-01-13 15:57  hinson0  阅读(622)  评论(0编辑  收藏  举报