xayan / dataflow
数据操作库
v1.0.1
2018-09-10 20:47 UTC
Requires (Dev)
- phpunit/phpunit: ^7.3
This package is auto-updated.
Last update: 2024-09-11 15:36:49 UTC
README
多功能数据操作库
数据操作库旨在,嗯,操作数据。该库引入了两个主要类:Entity 和 EntityCollection。第一个用于累积数据,第二个允许对实体进行批量操作。但这还不是全部,该库的另一个特点是数据导入/导出。目前仅支持CSV文件,但将来会有更多。这样,您可以轻松创建脚本,导入一些数据,处理它,然后以所需的形式(字符串或文件)输出。
安装
通过composer提供包
composer require xayan/dataflow
用法
假设以下CSV文件
λ cat your_file.csv
id,firstName,lastName,age
1,John,Doe,10
2,Mickey,Mouse,50
3,Philip J.,Fry,25
现在,假设我们想要筛选出仅包含成人的数据。此外,我不喜欢名字和姓氏分开。让我们将其更改为
<?php require_once 'vendor/autoload.php'; use DataFlow\Data\Entity; use DataFlow\IO\CSV\Export; use DataFlow\IO\CSV\ExportPolicy; use DataFlow\IO\CSV\Import; use DataFlow\IO\CSV\ImportPolicy; $file = 'your_file.csv'; $header = fgetcsv(fopen($file, 'r')); // This will create ImportPolicy that will import all available columns, using file header as a reference: $importPolicy = ImportPolicy::fromHeader($header); $collection = Import::fromFile($file, $importPolicy); $newCollection = $collection->filter(function(Entity $entity) { // Select only entities that contain the 'age' property and its value is >= 18 return $entity->has('age') && $entity->get('age') >= 18; })->map(function(Entity $entity) { // Set a new property $entity->set('name', $entity->get('firstName') . ' ' . $entity->get('lastName')); // Remove properties $entity->remove('firstName'); $entity->remove('lastName'); // Remember to return it return $entity; }); // Create ExportPolicy automatically from an entity, so all data will be exported $exportPolicy = ExportPolicy::fromEntity($newCollection->get(0)); // Create a new file and write export contents to it $outputFile = fopen('another_file.csv', 'w'); Export::toStream($outputFile, $newCollection, $exportPolicy);
如果您执行此脚本,输出应如下所示
λ cat another_file.csv
id,age,name
2,50,"Mickey Mouse"
3,25,"Philip J. Fry"
功能
该库的当前版本是v1.0。仅实现了基本功能,但它们仍具有一些潜力。
现在它能做什么
- 每个实体可以具有任何数量的任意基本类型的属性
- EntityCollection实现了数据操作的基本函数,即:
each、map、count和filter - 从CSV导入和导出 - 您可以指定从哪些列/属性导入/导出数据,以及当数据缺失时是否抛出异常
- 已实现完整的单元测试,以确保未来的更改不会破坏当前功能
未来计划
- JSON支持
- PDO支持
- 子实体
- 类型定义
- 数据验证
脚注
该库是一个私人项目,我无法保证它总是100%正常工作。