09.24
php
saved
ian
Note
A first attempt at reasonably generic "audit" behaviour that tracks changes to database fields.
To use, set $this->auditable = array('field_to_be_audited'); in the model
A first attempt at reasonably generic "audit" behaviour that tracks changes to database fields.
To use, set $this->auditable = array('field_to_be_audited'); in the model
- <?php
- /**
- * Tracks changes made to fields of existing records
- */
- uses('Sanitize');
- uses('cake_log');
- class AuditBehavior extends ModelBehavior {
- /**
- * Data before the save was made
- * @var array
- */
- /**
- * Data as it will look after the save is made
- * @var array
- */
- /**
- * Changed data that must be stored to the associated audit table
- * @var array
- */
- /**
- * initialize - nothing at the moment
- */
- function setup( &$model ) {
- }
- /**
- * Check that the model:
- * Has any auditable fields at all
- * Is having an existing record edited (ignore new records completely)
- * Has an associated audits table (ignore those without completely)
- *
- * Array diffs to get changed data. If save is successful then stores those changes
- */
- function beforeSave( &$model ) {
- return true;
- }
- return true;
- }
- $this->before_save_data = $model->findById($model->id); // read populates $model->data which then screws up the save, so just don't use it!
- $this->after_save_data = $model->data;
- $this->changed_data[$model->name] = Set::diff($this->after_save_data[$model->name], $this->before_save_data[$model->name]);
- }
- /**
- * If there are changes to the underlying data for an auditable field then stores those changes to the audit table
- *
- */
- function afterSave( &$model ) {
- foreach($this->changed_data[$model->name] as $k => $v) {
- // check that the field is auditable
- continue;
- }
- $data['Audit'] = aa( 'model', low($model->name),
- 'model_id', $model->id, 'changed_by_id', $this->_returnUserId(), 'changed_by_model', $this->_returnUserType(),
- loadModel('Audit');
- if (!ClassRegistry::isKeySet('Audit')) { CakeLog::write('audit_behavior', 'Failed to load the audit model');
- } else {
- $Audit =& ClassRegistry::getObject('Audit');
- }
- if(!$Audit->create() || !$Audit->save($data)) {
- CakeLog::write('audit_behavior', 'auditable changes failed to save - changes were ' . serialize($data));
- }
- }
- }
- return true;
- }
- /**
- * Returns the ID of the person or account making the change. OthAuth specific method
- * @return integer
- */
- function _returnUserId() {
- if(Set::check($_SESSION['othAuth'][AUTH_SESSION_KEY], 'User')) {
- } else {
- }
- }
- /**
- * Returns the type of personmaking the change. OthAuth specific method
- * @return string, either user or account
- */
- function _returnUserType() {
- if(Set::check($_SESSION['othAuth'][AUTH_SESSION_KEY], 'User')) {
- return 'user';
- } else {
- return 'account';
- }
- }
- }
- ?>
Parsed in 0.161 seconds, using GeSHi 1.0.7.14