<?php
namespace App\Model\Behavior;
use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\ORM\Entity;
use Cake\ORM\Behavior;
use App\Controller\AppController;
/**
* Userstamp Behavior
* - Set Users.id to `created_user_id` when INSERT entity.
* - Set Users.id to `modified_user_id` when UPDATE entity.
* @author hyano@ampware.jp
* @link https://goo.gl/Z41W4H
*/
class UserstampBehavior extends Behavior
{
/**
* Event of before called save method
* @param Event $event
* @param Entity $entity
* @param array $options
* @return void
*/
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) {
$loggedUserId = AppController::$loggedUserId ?? null;
if ($entity->isNew()) $entity->created_user_id = $loggedUserId;
$entity->modified_user_id = $loggedUserId;
}
}
// In Table.
$this->addBehavior('Userstamp');
// In AppController.
public static $loggedUserId = null;
// After authority.
$user = $this->Auth->user();
AppController::$loggedUserId = $user['id'];