3 * Object Relational Mapping (ORM) "versioned" extension. Allows ORM objects to
4 * be revisioned instead of updated.
10 * @copyright (c) 2007-2008 Kohana Team
11 * @license http://kohanaphp.com/license.html
13 class ORM_Versioned
extends ORM
{
15 protected $last_version = NULL;
18 * Overload ORM::save() to support versioned data
23 public function save()
25 $this->last_version
= 1 +
($this->last_version
=== NULL ?
$this->object['version'] : $this->last_version
);
26 $this->__set('version', $this->last_version
);
33 foreach ($this->object as $key => $value)
40 $data[$this->foreign_key()] = $this->id
;
42 $this->db
->insert($this->table_name
.'_versions', $data);
49 * Loads previous version from current object
54 public function previous()
59 $this->last_version
= ($this->last_version
=== NULL) ?
$this->object['version'] : $this->last_version
;
60 $version = $this->last_version
- 1;
63 ->where($this->foreign_key(), $this->object[$this->primary_key
])
64 ->where('version', $version)
66 ->get($this->table_name
.'_versions');
70 $this->load_values($query->result(FALSE)->current());
77 * Restores the object with data from stored version
79 * @param integer version number you want to restore
82 public function restore($version)
88 ->where($this->foreign_key(), $this->object[$this->primary_key
])
89 ->where('version', $version)
91 ->get($this->table_name
.'_versions');
95 $row = $query->result(FALSE)->current();
97 foreach ($row as $key => $value)
99 if ($key === $this->primary_key
OR $key === $this->foreign_key())
101 // Do not overwrite the primary key
105 if ($key === 'version')
107 // Always use the current version
108 $value = $this->version
;
111 $this->__set($key, $value);
121 * Overloads ORM::delete() to delete all versioned entries of current object
122 * and the object itself
124 * @param integer id of the object you want to delete
127 public function delete($id = NULL)
131 // Use the current object id
132 $id = $this->object[$this->primary_key
];
135 if ($status = parent
::delete($id))
137 $this->db
->where($this->foreign_key(), $id)->delete($this->table_name
.'_versions');