用Yii框架实现AR类自动记录日志

  1. 定义一个新的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) { 
		//记录日志操作,需要在各个类中各自实现
	}
}


转载于:https://my.oschina.net/rongruoxzhl/blog/293230

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值