Yoan Blanc Sat Apr 16 09:18:13 -0400 2011
I created something to log the changes of some attributes and everything a row is updated a log line is written for it.
How I use that :
1 class ObserveModel extends Model {
2 static $log_changes = array('name', 'biz');
3 }
The dirty implementation (into Model).
1 public function assign_attribute($name, $value) {
2 if (in_array($name, static::$log_changes) &&
3 !isset($this->__logs[$name])
4 ) {
5 $attributes = $this->attributes();
6 $this->__logs[$name] = isset($attributes[$name]) ?
7 $attributes[$name] :
8 null ;
9 }
10 return parent::assign_attribute($name, $value);
11 }
12
13 protected function update($validate=true) {
14 $log = null;
15 if ($this->__logs && $this->is_dirty()) {
16 $dirty = $this->dirty_attributes();
17 $new = array_intersect_key($dirty,$this->__logs);
18 $old = array_intersect_key($this->__logs,$dirty);
19 if ($new && $old) {
20 $class = get_class($this);
21 $id = $this->id;
22 $log = compact('class', 'id', 'old', 'new');
23 }
24 }
25 $result = parent::update($validate);
26 if ($result && $log) {
27 $logger = $this->__classes['logger'];
28 $logger::info(json_encode($log));
29 }
30 return $result;
31 }
Yoan Blanc Sat Apr 16 09:25:58 -0400 2011
What do you want to do with that information might shape how it's done in the end. Do you have any details? I can suspect cache invalidation here.
Would you like to see more callback available for such things? http://www.phpactiverecord.org/projects/main/wiki/Callbacks
(1-2/2)
Subject: Checking attribute change in callback
I'm trying to track the changes to a particular field in a table. The easiest solution would be to create a database trigger but unfortunately that is not possible. Is there a way to check on save that a particular field has been changed? I'm assuming this would be done via a callback.