le0m/yii2-import

一个用于从文件导入数据的Yii2框架扩展

安装: 9

依赖: 0

建议者: 0

安全: 0

星星: 1

关注者: 1

分支: 0

开放问题: 0

类型:yii2-extension

v1.0 2018-05-04 15:45 UTC

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,
]