需求:
带yii框架下写一个定时任务,扫描某一目录$target下的json文件,并导入指定的数据库中
实现:
1.把需要入库的json文件放在指定目录$target下
2.执行定时任务,导入到mongo库Vote_teacher中
/opt/modules/php/bin/php /www/web/protected/yiic.php import VoteTeacher
3.定时任务代码:
/web/protected/commandsImportCommand.php
/**
* 导入mongo库到测试环境
*
* @author lizhihui
* @date 2018-4-9
* @console php www/web/protected/yiic.php import VoteTeacher> /tmp/abc1.txt
*/
class ImportCommand extends CConsoleCommand
{
public $target='/www/web/html/import/'; //扫描的目录
public $model; //入库的数据库对象
public function run($args) {
if (isset($args[0])) {
$this->showMessage("params error", 1);
exit;
}
$this->model = $args[0];
$this->import();
}
/**
* 分析用户回答的信息并按格式入库vote_answer
* @author lizhihui
* @date 2018-4-9
*/
private function import()
{
$files = scandir($this->target);
//读取目录下文件
foreach ($files as $key => $val) {
$val = pathinfo($val);
$extension = $val['extension'];
//过滤掉非json格式
if($extension!='json'){
continue;
}
$filePath=$this->target.$val['basename'];
$fp=fopen($filePath,'r');
$content='';
while (!feof($fp)){
$content.=fread($fp, filesize($filePath)/10);//每次读出文件10分之1
//进行处理
}
$arr=json_decode($content);
if(empty($arr)){
$this->showMessage("no data to import");
die();
}
//实例化不同数据库
$tag=true;
foreach ($arr as $key => $val) {
//存储
$aVal = (array)$val;
$model = new $this->model;
if($model instanceof SMongodb){//动态字段存储
foreach ($aVal as $k => $v) {
$model->$k=$v;
}
}else{//非动态字段存储
$model->attributes=$aVal;
}
if(!$model->save()){
$tag=false;
}else{
unset($model); //销毁一个对象,再次使用的时候会new一个新的
}
}
}
if(!$tag){
$this->showMessage("some error in import");
}else{
$this->showMessage('import success!');
}
}
/**
* 信息输出
* @author lizhihui
* @date 2018-4-9
*/
private function showMessage($str, $err = 0) {
if (!$str) {
return false;
}
if ($err) {
echo "[ERROR]";
} else {
echo "[SUCCESS]";
}
echo date("Y-m-d H:i:s", time()) . " " . $str . "\n";
}
}