yiic提供了创建yii应用的各种方法。有时候可能需要自己定义一个命令来提高开发效率。
关于配置文件。
By default, if an application is created using the yiic webapp tool, the configuration for
the console application will be protected/config/console.php. Like a Web application
configuration file, this file is a PHP script which returns an array representing the prop-
erty initial values for a console application instance. As a result, any public property of
CConsoleApplication can be configured in this file.
Because console commands are often created to serve for the Web application, they need
to access the resources (such as DB connections) that are used by the latter. We can do
so in the console application configuration file like the following:
return array(
......
’components’=>array(
’db’=>array(
......
),
),
);
As we can see, the format of the configuration is very similar to what we do in a Web ap-
plication configuration. This is because both CConsoleApplication and CWebApplication
share the same base class.
控制台的命令配置文件是应用的protected/config/console.php文件,例如我们想使用数据库
<?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',
// application components
'components'=>array(
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
/*
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
*/
),
);
在配置文件中开启相应的数据就可以了。
这里提供简单的例子来讲述如何控制yiic控制台,自定义自己的命令。
关于类文件
存放位置
/protected/commands
类的定义规则
必须集成CConsoleCommand类
例如
TestCommand.php
<?php
class TestCommand extends CConsoleCommand
{
public function getHelp()
{
return '这里显示命令的帮助信息';
}
/**
* Execute the action.
* @param array command line parameters specific for this command
*/
public function run($args)
{
if(!isset($args[0]))
$this->usageError('请输入参数.');
echo('你输入的参数是 :\n');
var_dump($args);
}
}
/www/yii_dev/testwebap/protected# php yiic test p1 p2 p3
你输入的参数是 :\narray(3) {
[0]=>
string(2) "p1"
[1]=>
string(2) "p2"
[2]=>
string(2) "p3"
}
/www/yii_dev/testwebap/protected# php yiic test
Error: 请输入参数.
这里显示命令的帮助信息
框架中的代码就是最好的例子,如果要写控制台命令,可以仔细研读。
http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.console