wizaplace/collection-diff

此包已被废弃且不再维护。没有建议的替代包。

Collection Diff 允许您比较两个数据集以找到要执行的操作:创建、更新或删除数据。

1.0.0 2019-03-12 08:07 UTC

This package is auto-updated.

Last update: 2021-06-15 14:00:35 UTC


README

Collection Diff 允许您比较两个数据集以找到要执行的操作:创建、更新或删除数据。

要求

  • PHP ^7.1

安装

composer install wizaplace/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