rhuett/csvie
Composer 安装命令:
composer require rhuett/csvie
包简介
Csvie is a simple CSV file parser made for Laravel. Csvie is based on LeagueCSV, and can quickly import data to, and export data from, a MySQL database. It also gives you a handy abstract class for quickly sanitizing and scrubbing your CSV files prior to insertion.
README 文档
README
Csvie is a simple CSV file parser made for Laravel 7. Csvie is based on LeagueCSV, and can quickly import data to, and export data from, a MySQL database. It also gives you a handy abstract class for quickly sanitizing and scrubbing your CSV files prior to insertion.
How it works
Csvie is meant to quickly load CSV files with more than a few thousand rows of data into a MySQL database. The idea behind how this works is simple:
- You upload the CSV files onto your server.
- Use Csvie to chunk the files into smaller pieces. Chunking will be done by rows of data, instead of file globs.
- Write a custom CSV scrubber to clean data from the chunked files, then overwrite these files on the server.
- Note that you do not have to use the included HashCsvCleaner implementation. You are free to write your own using the Rhuett\Csvie\Contracts\CsvieCleaner interface.
- Directly load the clean files into your MySQL database directly using the Load Data statement.
Installation
Via Composer:
$ composer require rhuett/csvie
$ php artisan vendor:publish --provider="Rhuett\Csvie\CsvieServiceProvider"
Make sure to add the following line to your app/config/database.php file:
'mysql' => [ 'driver' => 'mysql', // ... 'options' => extension_loaded('pdo_mysql') ? array_filter([ // ... PDO::MYSQL_ATTR_LOCAL_INFILE => true, ]) : [], ],
Once you have finished these configuration changes, don't forget to run:
$ php artisan config:cache
Note that if you are getting errors about this not being enabled on both the client and server side, then you may also need to edit mysql.cnf:
# File Location: /etc/mysql/mysql.conf.d/mysql.cnf
# Add the following to the bottom of the file:
[server]
local_infile=true
...and run:
$ sudo systemctl restart mysql
Usage
Single CSV file import example, using a controller's store method:
public function store(Request $request) { $csvie = new Csvie; // note: you can pass an array of config overrides if needed $modelInstance = new Model; $referenceData = 'Whatever I want'; // note: reference data is optional // Note: You can pass an array for both column and model UIDs if you need to verify against multiple columns $cleaner = new ModelCleaner( 'ID', // column name from CSV file to match 'model_id', // model ID to verify against column name $modelInstance, $referenceData ); $fileName = $request->file->store('/', 'uploads'); // move uploaded file from /temp into permanent storage $chunkedFiles = $csvie->chunkFiles( $csvie->getStorageDiskPath('uploads').$fileName ); foreach($chunkedFiles as $chunk) { $chunkData = $csvie->readCsvFile($chunk); $cleanData = $cleaner->scrub($chunkData); $cleanFile = $csvie->saveCsvFile($chunk, $cleanData); $csvie->importCSV($cleanFile, $modelInstance); } $csvie->clearStorageDisk(); // clear out leftover uploaded file along with its chunks return view('view.index')->with([ 'models' => Model::all() ]); }
Making your own Csvie scrubber:
Simply run:
$ php artisan make:cleaner ModelNameCleaner
...and you should get a new file that looks like the one below in the App\Services\CsvCleaners directory. Note that the extra comments displayed here will not be included in newly generated files.
<?php namespace App\Services\CsvCleaners; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Rhuett\Csvie\Cleaners\HashCsvCleaner; /** * Class ModelCleaner. * * An abstract CsvieCleaner implementation using a custom scrubbing technique based on your needs. */ class ModelCleaner extends HashCsvCleaner { /** * Custom made function used to clean CSV data. * * @param array $rowData - The current row of data pulled from your CSV. * @param ?\Illuminate\Support\Collection $foundModels - Matched model(s) based on your CSV, otherwise contains null. * @param array $newModel - An empty model indexed with appropriate keys based on your model. * @param \Illuminate\Support\Carbon $date - The current date used for timestamps. * @param mixed $optionalData - Any custom data that you want to reference in the scrubber. * @return array|null */ protected function scrubber(array $rowData, ?Collection $foundModels, array $newModel, Carbon $date, $optionalData) { // Run checks on $rowData here. Validate, cleanse or completely change! // Use parent::updateValue() if you have many possible ways to update a single value within $rowData. Check the function for more information. // Return any changes, otherwise return $rowData to make no changes. // Return null if you want to remove the data completely. // Note: Duplicated headers will be automatically renamed in $rowData. // Ex: Header -> Header-1 -> Header-2 ... // Note: Since we are not using Eloquent, we will need to manage our timestamps manually. // This is why a Carbon datetime instance is passed as a parameter. } }
Note: If you would like to change the CsvCleaner directory, you can edit the csvie config file in your app's config directory.
Don't forget to add the cleaners directory to your composer.json file (if needed):
... "autoload": { ... "classmap": [ ... "app/Services" ] }, ...
Making your own CSV cleaner:
If you want a completely custom CSV Cleaner, then you can make your own implementation based on the Rhuett\Csvie\Contracts\CsvieCleaner contract like so:
use Illuminate\Support\Collection; use Rhuett\Csvie\Contracts\CsvieCleaner as CsvieCleanerContract; use Rhuett\Csvie\Traits\CsvieHelpers; /** * Class MyCsvCleaner. * * An abstract CsvieCleaner implementation using a custom scrubbing technique based on your needs. */ abstract class MyCsvCleaner implements CsvieCleanerContract { use CsvieHelpers; // Not needed, review trait to see if it will help you. /** * Cleans the data within a CSV record to match what's expected by the database. * * @param \Illuminate\Support\Collection $data * @return \Illuminate\Support\Collection */ public function scrub(Collection $data): Collection { // Clean all the data } }
Change log
Please see the changelog for more information on what has changed recently.
Testing
$ composer test
Contributing
Please see contributing.md for details and a todolist.
Security
If you discover any security related issues, please email im.ryan@protonmail.com instead of using the issue tracker.
Credits
- Ryan Huett: Project Author
- LeagueCSV: For making working with CSV's easy
- Laravel Collection Macros: For their succinct filterMap collection macro
License
MPL-2.0. Please see the license file for more information.
rhuett/csvie 适用场景与选型建议
rhuett/csvie 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 60 次下载、GitHub Stars 达 0, 最近一次更新时间为 2020 年 06 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「Csvie」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 rhuett/csvie 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 rhuett/csvie 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 rhuett/csvie 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Alfabank REST API integration
Laravel package for Accurate Online API integration.
Shared RCX Laravel DataTables UI and configuration helpers.
Boot a Laravel project on any machine with one command: app:serve installs missing tools (PHP, Node, Composer, Herd, Docker), creates .env, sets up the database, runs migrations, builds assets, starts a queue worker and serves via Herd, Sail or artisan serve; app:down cleanly stops everything it sta
Branded, diagnostic error pages (500, 403, 404, 419, 503) for Filament — native Filament UI, dark mode and translations out of the box.
Turn any PDF into a Pingen-ready A4 letter (generated address cover page + A4 normalisation + safe margins) and send it through the Pingen print & mail API. Laravel-first.
统计信息
- 总下载量: 60
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MPL-2.0
- 更新时间: 2020-06-25