yii cli模式 杂记

来源:互联网 发布:淘宝宝贝主图更换技巧 编辑:程序博客网 时间:2024/06/16 13:01

按照网络上一般的套路,就是在网站根目录下,新建一个php文件,例如index_cli.php,内容如下:

<?php$yiic=dirname(__FILE__).'/../yii/framework/yiic.php';$config=dirname(__FILE__).'/protected/config/console.php';// remove the following line when in production modedefined('YII_DEBUG') or define('YII_DEBUG',true);require_once($yiic);Yii::createConsoleApplication($config)->run();

config目录下的console.php或者main.php都是可以。关键的参数配置正确就可以,例如数据库连接。

然后,在protected/commands下建立一个类文件,例如TestCommand.php,内容如下:

<?phpclass TestCommand extends CConsoleCommand{    public function actionIndex(){        $DbConnection = Yii::app()->db;        $sqlstr = "select * from test";        $command = $DbConnection->createCommand($sqlstr);        $viewdata = $command->queryAll();        foreach ($viewdata as $key => $val){            echo $val['leftmoney'];        }    }}

然后,在命令行运行:

php index_cli.php test index

就可以看到sql语句的内容。

但发现踩了几个坑。

第一坑:
PHP Warning: PHP Startup: Invalid library (maybe not a PHP library) ‘mbstring.so’ in Unknown on line 0

这个是由于php编译时修改了php.ini导致,最后修改php.ini,把extension=mbstring.so屏蔽,即在最前面加;,然后重启php-fpm,如果用apache的,直接重启apache。就可以解决问题。(编译了新的 php模块进来后,不一定要增加extension的配置)

第二坑:
发现网上很多介绍在入口文件要加入:

Yii::createConsoleApplication($config)->run();

但发现加了后反而会出现

Yii application can only be created once.

的错误,去除后却能正常运行。

所以,最终修改成index_cli.php,内容如下:

<?php$yiic=dirname(__FILE__).'/../yii/framework/yiic.php';$config=dirname(__FILE__).'/protected/config/console.php';// remove the following line when in production modedefined('YII_DEBUG') or define('YII_DEBUG',true);require_once($yiic);

command下的文件不变,然后在命令行运行:

php index_cli.php test index

index_cli.php为入口文件,test是protected/command文件夹下的类名,index是test类下的action方法。

原创粉丝点击