babeuloula / collection-diff
该包已被废弃且不再维护。没有建议的替代包。
Collection Diff 允许您比较两个数据集合,以找到需要执行的操作:创建、更新或删除数据。
1.0.3
2022-12-27 16:01 UTC
Requires
- php: ^7.1||^8.1
- symfony/serializer: ^2.7||^3.0||^4.0||^5.0||^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.14
- phpstan/phpstan: ^0.11.2
- phpunit/phpunit: ^8.0
Suggests
- symfony/framework-bundle: Needed to use Collection Diff's bridge
This package is auto-updated.
Last update: 2024-03-04 09:46:41 UTC
README
Collection Diff 允许您比较两个数据集合,以找到需要执行的操作:创建、更新或删除数据。
要求
- PHP ^7.1
安装
composer install babeuloula/collection-diff
用法
如果您想比较数据库和表单(如 $_POST)之间的数据
<?php // Collection from your database $from = [ new FooObject("foo", "category1", 10.5), new FooObject("bar2", "category2", 9.5), new FooObject("bar1", "category1", 9.5), new FooObject("barFoo", "category1", 9.5), new FooObject("barFooBar", "category1", 9.5), ]; // Collection from you form like $_POST $to = [ [ "name" => "foo", "category" => "category1", "price" => 11.5 ], [ "name" => "bar2", "category" => "category2", "price" => 9.5, ], [ "name" => "bar1", "category" => "category2", "price" => 9.5, ], [ "name" => "fooBar", "category" => "category3", "price" => 8.5, ], ];
您需要调用 CollectionDiff::compare
来执行比较,然后调用 CollectionDiff::getActions
来获取操作。
CollectionDiff::compare
的第一个参数是一个包含所需主键的数组,Collection Diff 需要这些主键来执行比较并检查这些键的一致性。
您的对象将被标准化以便进行比较。
请参考上面的示例。
Symfony
如果您想在您的 Symfony 项目中使用 Collection Diff,您可以使用桥接器 Wizaplace\CollectionDiff\Bridge\CollectionDiffBundle
。
$container ->get(\Wizaplace\CollectionDiff\CollectionDiff::class) ->compare(['name', 'category'], $from, $to, false, true) ->getActions();
独立
$mySerializer = new FooSerializer(); $collectionDiff = new Wizaplace\CollectionDiff\CollectionDiff($mySerializer); $collectionDiff->compare(['name', 'category'], $from, $to, false, true); $collectionDiff->getActions(); // Or $collectionDiff->getNothing(); $collectionDiff->getCreate(); $collectionDiff->getUpdate(); $collectionDiff->getDelete();
返回以下结果
array (size=4)
1 =>
array (size=1)
0 =>
array (size=3)
'name' => string 'bar2' (length=4)
'category' => string 'category2' (length=9)
'price' => float 9.5
2 =>
array (size=1)
0 =>
array (size=3)
'name' => string 'fooBar' (length=6)
'category' => string 'category3' (length=9)
'price' => float 8.5
3 =>
array (size=2)
0 =>
array (size=3)
'name' => string 'foo' (length=3)
'category' => string 'category1' (length=9)
'price' => float 11.5
1 =>
array (size=3)
'name' => string 'bar1' (length=4)
'category' => string 'category2' (length=9)
'price' => float 9.5
4 =>
array (size=1)
0 =>
array (size=3)
'name' => string 'barFoo' (length=6)
'category' => string 'category1' (length=9)
'price' => float 9.5