CakePHP LogsBehavior
by Michael Mafort on jan.18, 2009, under CakePHP
Bom seguindo uma necessidade de registrar log de tudo que é feito em uma aplicação eu desenvolvi um behavior para ser usado no cakephp, muito simples e prático. Ele registra alterações nas tabelas como insert, update e delete.
Update -> Grava o registro antigo e o novo.
Insert -> Grava o novo registro.
Delete -> Grava o registro antigo.
Em todos os logs são gravados o id do usuário logado que fez a alteração, a data da alteração, o nome do model que foi alterado e a ação que foi efetuada (add, edit ou delete)
A unica parte que deverá ser editada de acordo com seu sistema de autenticação é o relacionamento com o model que está utilizando na autenticação.
Vamos ao que interessa então:
Criando a tabela no banco de dados, estou utilizando o mysql.
1 2 3 4 5 6 7 8 9 10 11 12 13 | CREATE TABLE `logs` ( `id` int(10) unsigned NOT NULL auto_increment, #este é o meu id do usuario logado, meu model de autenticação chama-se authuser `authuser_id` int(10) unsigned NOT NULL, `model` varchar(60) default NULL, `action` varchar(20) default NULL, `old_data` text, `new_data` text, `created` datetime default NULL, PRIMARY KEY (`id`), KEY `logs_FKIndex1` (`authuser_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; |
Crie o log model models/log.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Log extends AppModel { var $name = 'Log'; //The Associations below have been created with all possible keys, those that are not needed can be removed var $belongsTo = array( 'Authuser' => array('className' => 'Authuser', 'foreignKey' => 'authuser_id', 'conditions' => '', 'fields' => '', 'order' => '' ) ); } |
Criando agora o behavior log: models/behaviors/logs.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | /** * Behavior for log actions of tables. * * Behavior to simplify logs * * PHP versions 5 * * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright 2005-2008, Criasol Ltd. * @link http://www.criasol.com.br * @since 12-07-2009 * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ /** * Behavior to register log to all actions in your table model * */ App::import('Model','Log'); App::import('Component', 'Session'); class LogsBehavior extends ModelBehavior { /** * Current model * * @var Object */ private $Model; /** * Session component object * * @var Object */ private $Session; /** * Old data * last data from model before modified * * @var array */ private $_oldData; /** * New data * new value from model after modified * * @var array */ private $_newData; /** * Model log * * @var Object */ private $Log; /** * Action * type of action called * * @var string */ private $_action; /** * Deleted id * id from data to delete * * @var int */ private $_deletedId; /** * Setup method * * Configure this behavior * * @param ObjectModel $model * @param array $config */ public function setup(&$model, $config = null){ $this->Model = $model; $this->Session = new SessionComponent(); $this->Log = new Log(); } /** * Before save * * @param ObjectModel $model * @return boolean true */ public function beforeSave(&$model){ if( is_numeric($this->Model->id) ){ $this->_action = 'edit'; $newData = $this->Model->find('first', array('conditions'=> array( "{$this->Model->name}.id" => $this->Model->data[$this->Model->name]['id'] ) ) ); foreach( $newData[$this->Model->name] as $input => $value ){ $this->_oldData .= "$input :: $valuen"; } } else $this->_action = 'add'; return true; } /** * After save * * @param objectModel $model * @param string $created * @return boolean true */ public function afterSave(&$model, $created){ $newData = $this->Model->read(null, $this->Model->id); foreach( $newData[$this->Model->name] as $input => $value ){ $this->_newData .= "$input :: $valuen"; } $this->write(); return true; } /** * Before delete * * @param objectModel $model * @param boolean $cascade * @return boolean true */ public function beforeDelete(&$model, $cascade=true){ $this->_action = 'delete'; $this->_deletedId = $this->Model->data[$this->Model->name]['id']; $newData = $this->Model->read(null, $this->_deletedId ); foreach( $newData[$this->Model->name] as $input => $value ){ $this->_oldData .= "$input :: $valuen"; } return true; } /** * After delete action * * @param ObjectModel $model * @return boolean true */ public function afterDelete(&$model){ $this->write(); return true; } /** * Write log * * @return void */ public function write(){ if( $this->Model->name == 'Log' ) return true; $this->Log->id = null; $this->Log->save(array( 'Log'=>array( 'authuser_id' => $this->Session->read('Authuser.id'), 'model' => $this->Model->name, 'action' => $this->_action, 'old_data' => $this->_oldData, 'new_data' => $this->_newData ) )); } } ?> |
Na linha 183 edite o valor de session read para o valor do id do seu usuário logado.
Para funcionar com php 4, retire os public’s e private’s do código, em functions deixe vazio nas variáveis substitua por var.
Agora para salvar os logs basta inserir em seu model que deseja salvar os logs a variável:
public $actsAs = array(’Logs’);
Por hoje é só…
Abraços,
janeiro 18th, 2009 on 9:43 am
Bom kra.. oq dizer?!
Ficou simplismente phoda!! muito bom kra…
Parabéns!
julho 15th, 2010 on 4:31 pm
Amigo, bela iniciativa… fiquei somente com uma dúvida, esse behavior funciona no cake 1.3 ?
agosto 12th, 2010 on 3:04 pm
Ainda não testei, assim que tiver resultados postarei para mais detalhes.