Skip to content

Instantly share code, notes, and snippets.

@szabomikierno
Last active December 28, 2017 16:07
Show Gist options
  • Select an option

  • Save szabomikierno/2e2e9fcc00284d78cc152cfbe9ae0612 to your computer and use it in GitHub Desktop.

Select an option

Save szabomikierno/2e2e9fcc00284d78cc152cfbe9ae0612 to your computer and use it in GitHub Desktop.
Model logger, extended by Model Observers
<?php
// A class extended by Model Observers to do some general automatic logging
// whenever a model has been touched.
namespace App\Infrastructure\Utility;
use App\Infrastructure\Model\Log;
use Auth;
class ModelLogger {
protected $log;
protected $request;
protected $requester;
// The observer methods we wish to log. Note that these methods must be protected
// so calling them will actually call the __call magic method
// In the observer method we can add additional data to the log
private $logged = ['created' , 'updated', 'deleted', 'restored'];
public function __construct(){
$this->log = new Log;
$this->request = request();
$this->requester = Auth::user();
if($this->requester) {
$this->log->user_id = $this->requester->id;
}
$this->log->ip_address = $this->request->ip();
$this->log->url = $this->request->path();
// Additional data I can log
}
public function __call($method,$arguments) {
if(in_array($method, $this->logged)){
$result = call_user_func_array(array($this,$method),$arguments);
$model = $arguments[0];
$this->log->affected_row_id = $model->id;
$this->log->affected_db_table = $model->getTable();
$this->log->affected_model = get_class($model);
$this->log->HTTP_method = $this->request->method();
$this->log->save();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment