console 是命令行操作,对于frontend和backend是基于web的操作,最终的结果是一样的,都是传递数据给php,下面做一个例子:
1.安装frontend ,然后执行init,可以参看这里:
2.新建文件夹/console/controllers/script,然后新建文件TestController.php
3.编辑文件内容:
namespace console\controllers\script;
use Yii;
use yii\console\Controller;
use fec\helpers\CDate;
use fec\helpers\CConfig;
use appadmin\code\Website\models\WebsiteBaseInfo;
class TestController extends Controller{
public $_mongodbdb;
public function actionGetbegindate(){
echo '2015-05-20';
}
public function actionCreatecollindexer(){
echo 'create Coll index success';
}
public function actionMy($param1,$param2=''){
echo "param1:".$param1;
echo "param2:".$param2;
}
}
4.回到yii advanced的根目录执行:
[root@services datacenter_1000]# ./yii script/test/my 111 2222
param1:111param2:2222
[root@services datacenter_1000]#
解读:
script/test/my 这个和web一样,对应到上面创建的TestController的 actionMy()方法,111为传递的第一个参数,222给传递的第二个参数。
到这里,基本就一个helloworld就写好了,其他的和web没有什么两样。
5.在模块中使用console:(下面是一个在模块TA中使用console的例子)
'modules'=>[
'ta' => [
'class' => 'appadmin\code\Ta\Module',
'params'=> [
'channel_type' => [
'ppc' => 'PPC类型',
],
],
],
]
在ta模块的Module中添加代码:
namespace appadmin\code\Ta;
use Yii;
class Module extends \fec\AdminModule{
public function init(){
//echo 1;exit;
# 以下代码必须指定
# web controller
if (Yii::$app instanceof \yii\web\Application) {
$this->controllerNamespace = __NAMESPACE__ . '\\controllers';
# console controller
} elseif (Yii::$app instanceof \yii\console\Application) {
$this->controllerNamespace = __NAMESPACE__ . '\\console';
}
parent::init();
}
}
通过上面判断是console的application还是web的application,取执行相应的controller
譬如我写的一个导入excel的脚本(在ta模块中):
namespace appadmin\code\Ta\console\import;
use Yii;
use appadmin\code\Ta\models\WebsiteChannel;
use yii\console\Controller;
use fec\helpers\CExcel;
class ExcelController extends Controller{
public function actionChannel(){
$channel_excel_file = Yii::getAlias('@appta/var/import/channel.xlsx');
$arr = CExcel::getExcelContent($channel_excel_file);
//var_dump($arr);
$i = 0;
foreach($arr as $one){
$i++;
if($i == 1){
continue;
}
$channel = trim($one['A']);
$channel_child = trim($one['B']);
$domain = trim($one['C']);
$one = WebsiteChannel::find()->where([
'channel' => $channel,
'channel_child' => $channel_child,
'domain' => $domain,
])->one();
if(!$one['id']){
$WebsiteChannel = new WebsiteChannel;
}else{
continue;
}
//SEO>SEM>KOL>SNS
$WebsiteChannel->channel = $channel;
$WebsiteChannel->channel_child = $channel_child;
$WebsiteChannel->domain = $domain;
$WebsiteChannel->created_person = 'program_script';
$WebsiteChannel->save();
unset($WebsiteChannel);
}
}
}
我新建一个shell文件
appta/shell/import/channel.sh,内容为:
#!/bin/sh
DIR=$(cd `dirname $0`; pwd)
$DIR/../../../yii ta/import/excel/channel
然后执行这个shell就会执行上面的模块Ta里面的console部分。