Skip to content

Instantly share code, notes, and snippets.

@motooka
Last active October 31, 2015 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motooka/ce7a2afea442391a242c to your computer and use it in GitHub Desktop.
Save motooka/ce7a2afea442391a242c to your computer and use it in GitHub Desktop.
CakePHP3.x : Save simple audit trails (userIDs) on insert/update
<?php
/**
* for CakePHP 3.x
* Activate this behavior on your models to set values (user ID) to "created_by" and "modified_by" columns on insert/update.
* see http://book.cakephp.org/3.0/en/orm/behaviors.html#using-behaviors
*
* Please note that if you use such models from Shells(CLI), these values will be set to null.
*
* You also have to set static property "sessionUserID" on AppController::initialize().
*/
namespace App\Model\Behavior;
use Cake\ORM\Behavior;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\ORM\Entity;
use Cake\Log\Log;
class AuditBehavior extends Behavior
{
public function beforeSave(Event $event, Entity $entity)
{
$sessionUserID = AppController::$sessionUserID;
if(empty($entity->id)) {
//Log::debug('is going to insert');
$entity->created_by = $sessionUserID;
}
else {
//Log::debug('is going to update');
}
$entity->modified_by = $sessionUserID;
}
}
<?php
class AppController extends Controller
{
public static $sessionUserID = null;
public function initialize()
{
parent::initialize();
self::$sessionUserID = $this->Auth->user('id');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment