[英]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.