Рубрики
Uncategorized

Платформа Yii, сканирует файлы из каталогов в базы данных

Автор оригинала: David Wong.

Требовать:

Напишите временную задачу с помощью платформы Yii, отсканируйте файл JSON в каталоге $target и импортируйте его в указанную базу данных

Осуществление:

1. Поместите файлы JSON, которые необходимо сохранить в указанном каталоге, в $target 2. Выполните задачи синхронизации и импортируйте их в библиотеку Mongo Vote_teacher

/opt/modules/php/bin/php /www/web/protected/yiic.php import VoteTeacher

3. Код задачи синхронизации:/web/protected/commandsImportCommand.php

 /tmp/abc1.txt
 */
class ImportCommand extends CConsoleCommand 
{

    Public $target='/www/web/html/import/'; //scanned directory

    Public $model; // database objects into the database

    public function run($args) {

        if (isset($args[0])) {
            $this->showMessage("params error", 1);
            exit;
        }
        $this->model = $args[0];
        $this->import();
    }

    /**
     * Analyse the user's answers and put them in the form of vote_answer
     * @author      lizhihui
      * @date        2018-4-9
     */
    private function import() 
    {
        $files = scandir($this->target);
        // Read the files under the directory
        foreach ($files as $key => $val) {
            $val = pathinfo($val);
            $extension = $val['extension'];
            // Filter out non-json formats
            if($extension!='json'){
                continue;
            }

            $filePath=$this->target.$val['basename'];
            $fp=fopen($filePath,'r');
            $content='';
            while (!feof($fp)){
                $content. = FREAD ($fp, filesize ($filePath) / 10); // 1/10 of every read-out file
            // Processing
            }
            $arr=json_decode($content);
            if(empty($arr)){
                $this->showMessage("no data to import");
                die();
            }

            // Instantiate different databases
            $tag=true;
            foreach ($arr as $key => $val) {                
                // storage
                $aVal = (array)$val;
                $model = new $this->model;
                If ($model instance of SMongodb) {// dynamic field storage
                    foreach ($aVal as $k => $v) {
                        $model->$k=$v;
                    }
                } Other {// Non-dynamic Field Storage
                    $model->attributes=$aVal;
                }

                if(!$model->save()){
                    $tag=false;
                }else{
                    Unset ($model); /// Destroy an object, which will be new when reused
                }
            }

        }
        if(!$tag){
            $this->showMessage("some error in import");
        }else{
            $this->showMessage('import success!');
        }
    }    


    /**
     * Information Output
     * @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";

    }
}

Оригинал: “https://developpaper.com/yii-framework-scans-files-from-directories-into-databases/”