- 定义一个新的AR类MyActiveRecord并继承CActiveRecord类,然后定义日志处理事件RecordLog:
public function RecordLog($objEvent) { //记录日志操作,需要在各个类中各自实现 }
2. 在类初始化的时候为记录日志事件附加一个事件处理程序,即绑定日志记录事件:
public function init() { //绑定日记记录事件 $this->attachEventHandler(‘onRecordLog‘, array($this, ‘RecordLog‘)); parent::init(); }
3. 增加日志记录事件,即在绑定的日志记录事件中触发日志记录事件:
public function onRecordLog($objEvent) { $this->raiseEvent(‘onRecordLog‘, $objEvent); }
4. 增加记录变更的方法内(insert,update...)调用记录日志的事件,即重写基类的insert,update等方法,在记录更新成功后调用记录日志的事件,完成日志的记录:
public function addLogData($bFlush = false) { if($bFlush && $this->hasEventHandler(‘onRecordLog‘)) { $this->onRecordLog(new CEvent($this)); } $this->aLogs = array(); $this->nLogCount = 0; $this->nListId = null; $this->sListType = ‘‘; $this->nLogUser = null; $this->sLogDesc = ‘‘; }
重写insert方法:
public function insert($attributes = null) { $bIsSuccess = parent::insert($attributes); $this->addLogData($bIsSuccess); return $bIsSuccess; }
这样,其他model类在继承MyActiveRecord类后重写其RecordLog方法后,在更新对应model记录的时候,AR类就会自动记录信息变更的日志,从而保存下日志数据,以便其他程序对日志进行分析利用。
MyRecordRecord类的完整实现:
abstract class MyActiveRecord extends CActiveRecord { public function init() { //绑定日记记录事件 $this->attachEventHandler(‘onRecordLog‘, array($this, ‘RecordLog‘)); parent::init(); } public function insert($attributes = null) { $bIsSuccess = parent::insert($attributes); $this->addLogData($bIsSuccess); return $bIsSuccess; } public function update($attributes = null) { $bIsSuccess = parent::update($attributes); $this->flushLogData($bIsSuccess); return $bIsSuccess; } public function flushLogData($bFlush = false) { if($bFlush && $this->hasEventHandler(‘onRecordLog‘)) { $this->onAddRecordLog(new CEvent($this)); } } public function onRecordLog($objEvent) { $this->raiseEvent(‘onRecordLog‘, $objEvent); } public function RecordLog($objEvent) { //记录日志操作,需要在各个类中各自实现 } }
用Yii框架实现AR类自动记录日志
时间: 2024-10-11 00:53:02