le0m / yii2-import
一个用于从文件导入数据的Yii2框架扩展
v1.0
2018-05-04 15:45 UTC
Requires
- yiisoft/yii2: ~2.0.0
This package is auto-updated.
Last update: 2024-08-29 05:00:10 UTC
README
此扩展可以帮助您将CSV或JSON等文件中的数据导入到应用程序中。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令
composer require le0m/yii2-import
或将以下内容添加到composer.json的require部分。
"le0m/yii2-import": "*"
使用方法
此扩展提供从文件导入数据到数组或ActiveRecord等数据结构的支持。
首先,您必须创建一个Importer
,它需要一个reader
和一个importStrategy
才能工作,然后您可以导入
$importer = new Importer([ // this can be an array of strings to use as column names for the imported data, // `true` if the column names can be extracted from the file itself (the 'how' is specific to the implementation) // or `false` to disable and not use column names (default). 'columnNames' => [...], // see below for how to setup this 'reader' => [ 'class' => '\common\components\importer\CsvReader', ], // see below for how to setup this 'importStrategy' => [ 'class' => '\common\components\importer\ARImportStrategy', ] ]); // get the imported data $data = $importer->import();
导入器将使用选择的reader
实现读取文件,将每个元素传递给选择的importStrategy
实现。返回值是导入数据的数组。
如果importStrategy
对单个元素返回false
,则导入器将忽略它。
默认情况下,此扩展提供了两个读取器(CSV和JSON)和两个导入策略(数组到和ActiveRecord到)实现以供选择,但您可以通过实现相应的接口添加自己的。
导入CSV文件
CsvReader
接受以下属性
'reader' => [ 'class' => '\common\components\importer\CsvReader', // limit the max length of a single line to read from file // 0 means no limit 'lineLength' => 0, // character used to separate values on a single line 'valueDelimiter' => ",", // character used to enclose values 'valueEnclosure' => '"', // character used as escape in the values 'escapeCharacter' => "\\", ]
导入JSON
JsonImporter
没有特定属性
'reader' => [ 'class' => '\common\components\importer\JsonReader', ]
导入到ActiveRecord
ARImportStrategy
接受以下属性
'importStrategy' => [ 'class' => '\common\components\importer\ARImportStrategy', // name of the ActiveRecord class to use for the import 'className' => '...', // if you need custom code to handle loading data read from the file to the AR // (ex. column names from the file are different than property names from the AR // this function will be called for each element in the original file, // return false to not import the current element ([[Importer]] ignores false elements) 'loadProperties' => function ($model, $data) { ... }, // whether to automatically save the AR at the end of the import // AR with validation errors are returned anyway 'saveRecord' => true, ]