สิ่งผมเขียนไม่ใช่ best practice จริงๆ แล้วผมก็ไม่ค่อยแน่ใจว่ามันจะใช้ได้ดีหรือเปล่า แต่ว่าก็บันทึกไว้ก่อน. เว็บที่ผมเขียนมักจะต้องทำอะไรประเภทมี version control ด้วย แนวๆ wiki ดังนั้นถ้า model ช่วงแบ่งเบาภาระพวก version control ไปได้บ้าง ก็ทำให้ controller ดูรกน้อยลงไปมาก (หวังว่าแบบนั้น) ก่อนหน้านี้ CakePHP เคยมี behavior ด้วยช่วยเก็บ history มาให้ถ้าจำไม่ผิด แต่ตอนนี้หาไม่เจอแล้ว และเพื่อให้ได้อย่างใช้ตัวเองผมก็เลยใช้แค่ callback function.
model ที่ผมต้องการจำ history ชื่อ Textunit สมมุตว่า textunits เป็น table มี column ได้แก่ id และ string เอาแค่นี้ก็พอ เพื่อเป็นตัวอย่าง วิธีของผมก็คือสร้างขึ้นมาอีก table เลยชื่อ history_textunits โดยมี column ดังนี้ id, old_id, revision และ string
จากนั้นก็สร้าง code ใน app/model ตามนี้
<?php
class Textunit extends AppModel {
var $name = 'Textunit';
var $history = 'HistoryTextunits';
function beforeSave() {
if(!empty($this->id)) {
$historyModel = ClassRegistry::init($this->history);
$historyData = $this->findById($this->id);
$historyModel->record($historyData[$this->name]);
}
return true;
}
}
?>
และ
<?php
class HistoryTextunits extends AppModel {
var $name = 'HistoryTextunits';
function record($textunit) {
$history = array();
foreach($textunit as $k => $v) {
if($k == "id")
$k = "old_id";
$history[$k] = $v;
}
$this->create();
$this->save($history);
}
}
?>
แค่นี้เอง