Last active
October 31, 2015 07:02
-
-
Save motooka/ce7a2afea442391a242c to your computer and use it in GitHub Desktop.
CakePHP3.x : Save simple audit trails (userIDs) on insert/update
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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