简体   繁体   English

CakePHP 2.x 保存 model 时比较原始数据和修改数据

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

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.在 CakePHP 3.x 中,我在 Model.beforeSave 事件上实现了一个监听器。 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.当用户 model 被保存时,我通过收集脏(修改)字段来比较它,另外我检查字段值是否真的改变了。

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.现在我必须在 CakePHP 2.x 上执行类似的任务,其中 model 没有相同的 getDirty() 和 getOriginal() 函数。 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我准备了一个监听器并想使用 model 回调,但我坚持收集用户原始和修改后的字段数据进行比较

You could check the awesome list, on how behaviors like Logable do it.您可以查看很棒的列表,了解Logable之类的行为是如何做到的。 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. arrays 的手动过程比 3.x+ 实体类多一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM