簡體   English   中英

CakePHP 2.x 保存 model 時比較原始數據和修改數據

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

如果特定數據已被修改,我正在研究一種將信息存儲到數據庫的解決方案。 在 CakePHP 3.x 中,我在 Model.beforeSave 事件上實現了一個監聽器。 當用戶 model 被保存時,我通過收集臟(修改)字段來比較它,另外我檢查字段值是否真的改變了。

例子:

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;
  } 
}

現在我必須在 CakePHP 2.x 上執行類似的任務,其中 model 沒有相同的 getDirty() 和 getOriginal() 函數。 我准備了一個監聽器並想使用 model 回調,但我堅持收集用戶原始和修改后的字段數據進行比較

您可以查看很棒的列表,了解Logable之類的行為是如何做到的。 他們通常會在保存前對數據進行快照,然后將其與保存后的數據進行比較。 arrays 的手動過程比 3.x+ 實體類多一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM