导入和导出模型定义了处理导入或导出操作时使用的逻辑,分别扩展了 Backend\Models\ImportModel 和 Backend\Models\ExportModel 模型。这些模型旨在与 导入导出控制器 配合使用,但是,也可以直接在 PHP 中使用它们。
用于导入数据,您应该为此过程创建一个专用模型,该模型扩展了 Backend\Models\ImportModel 类。以下是一个示例类定义:
class SubscriberImport extends \Backend\Models\ImportModel
{
/**
* @var array rules to be applied to the data.
*/
public $rules = [];
public function importData($results, $sessionKey = null)
{
foreach ($results as $row => $data) {
try {
$subscriber = new Subscriber;
$subscriber->fill($data);
$subscriber->save();
$this->logCreated();
}
catch (Exception $ex) {
$this->logError($row, $ex->getMessage());
}
}
}
}该类必须定义一个名为 importData 的方法,用于处理导入的数据。
第一个参数 $results 将包含一个包含要导入的数据的数组。
第二个参数 $sessionKey 将包含用于请求的会话密钥。
| Method | Description |
|---|---|
logUpdated() | Called when a record is updated. |
logCreated() | Called when a record is created. |
logError(rowIndex, message) | Called when there is a problem with importing the record. |
logWarning(rowIndex, message) | Used to provide a soft warning, like modifying a value. |
logSkipped(rowIndex, message) | Used when the entire row of data was not imported (skipped). |
使用 importFile 方法手动处理从存储在磁盘上的本地文件导入。
$importModel = new MyImportClass;
$importModel->file_format = 'json';
$importModel->importFile('/path/to/import/file.json');如果文件来自上传文件 使用 Input facade 访问本地路径。
$importModel->importFile(
Input::file('file')->getRealPath()
);要导出数据,您应该创建一个扩展 Backend\Models\ExportModel 类的专用模型。以下是一个示例:
class SubscriberExport extends \Backend\Models\ExportModel
{
public function exportData($columns, $sessionKey = null)
{
$subscribers = Subscriber::all();
$subscribers->each(function($subscriber) use ($columns) {
$subscriber->addVisible($columns);
});
return $subscribers->toArray();
}
}该类必须定义一个名为exportData的方法,用于返回导出数据。第一个参数$columns是一个要导出的列名数组。第二个参数$sessionKey将包含用于请求的会话密钥。
使用 exportDownload 方法手动处理导出并返回下载响应。
$exportColumns = ['id', 'title'];
$exportModel = new MyExportClass;
$exportModel->file_format = 'json';
return $exportModel->exportDownload('myexportfile.json', ['columns' => $exportColumns]);导入和导出表单都支持自定义选项,这些选项可以通过表单字段引入,这些字段分别定义在导入或导出配置的 **form** 选项中。这些值随后会传递给导入/导出模型并在处理期间可用。
# config_import_export.yaml
import:
# ...
form: $/acme/campaign/models/subscriberimport/fields.yaml
export:
# ...
form: $/acme/campaign/models/subscriberexport/fields.yaml指定的表单字段将显示在导入/导出页面上。以下是 fields.yaml 文件的示例内容:
# fields.yaml
fields:
auto_create_lists:
label: Automatically create lists
type: checkbox
default: true上方名为auto_create_lists的表单字段的值可以在导入模型的importData方法内部使用$this->auto_create_lists访问。如果这是导出模型,该值将改为在exportData方法内部可用。
class SubscriberImport extends \Backend\Models\ImportModel
{
public function importData($results, $sessionKey = null)
{
if ($this->auto_create_lists) {
// Do something
}
// ...
}
}