CakePHP 2.x compare original and modified Data when model is saved

210 Views Asked by At

I'm working on a solution to store Information to the database if specific data has been modified. At CakePHP 3.x I implemented a listener on the Model.beforeSave Event. When a user model has been saved I compare it by collecting the dirty (modified) fields and additionaly I check if the fields value has really changed.

Example:

class CustomListener implements EventListenerInterface {

  public function implementedEvents() {
      return [
          'Model.beforeSave' => [
              'priority' => 600,
              'callable' => 'filterUserInfos',
          ],

      ];
  }

  public function filterUserInfos($event, $entity, $options) {
      $subject = $event->getSubject();
      if($subject->alias() == 'Users') {

          $modified_fields = array_flip($entity->getDirty());
          $observed_fields = [
            'firstname',
            'lastname',
            'email',
            'country_id',
            'language_id',
          ];
         
         // look if modified fields are in my observed list
         $matches = array_intersect_key($modified_fields, array_flip($observed_fields));
        
         if(!empty($matches)) {
            // if its dirty but its value didn't change... throw away
            foreach(array_keys($matches) as $attribute) {
                if($entity->$attribute == $entity->getOriginal($attribute)) {
                    unset($matches[$attribute]);
                }
            }
            if(!empty($matches)) {
               // call function to store to database
            }
         }
       }
    return true;
  } 
}

Now I have to do a similar task on CakePHP 2.x where the model doesn't have the same getDirty() and getOriginal() functions. I've prepared a listener and wanted to use model callbacks, but I'm stuck collecting the users original and modified fields data for comparing

1

There are 1 best solutions below

0
On

You could check the awesome list, on how behaviors like Logable do it. They usually take a snapshot of the data before the save, and compare it then to the data after the save. A bit more manual process for arrays than with 3.x+ entity classes.