As part of a recent project to reduce the number of “rogue” update statements issued when a Symfony form (with embedded forms) was saved I had to create an algorithm to compare two Doctrine_Record objects, to determine if an update should occur or not, so I thought I would share with the community.

Below is the logic, however it does not follow the DRY (Don’t Repeat Yourself) principle, I did it this way on purpose so you can easily implement into your codebase.


$array1 = array('id' => 1, 'name' => 'element1');

$array2 = array('id' => 1, 'name' => 'element1');

// For this too work, these objects must extend from Doctrine_Record class

$object1 = new Object();

$object2 = new Object();

// fromArray will hydrate the object with values in the array

$object1->fromArray($array1);

$object2->fromArray($array2);

// Due to PHP being a loosely typed language, there were instances where, after hydration, some is_numeric scalars were strings or ints

// So this will ensure all is_numeric scalars are ints, which ensures an apples to apples comparison

$objectArray1 = array_map(function($value) { return (is_numeric($value)) ? (int) $value : $value; }, $object1->toArray(false));

$objectArray2 = array_map(function($value) { return (is_numeric($value)) ? (int) $value : $value; }, $object2->toArray(false));

$hash1 = md5(serialize($objectArray1));

$hash2 = md5(serialize($objectArray2));

$compareStatus = ($hash1 === $hash2) ? true : false;