yano3nora
11/14/2017 - 5:55 AM

[cakephp: UserstampBehavior] Model behavior that writing created / modified user's id to entity before save. #cakephp

[cakephp: UserstampBehavior] Model behavior that writing created / modified user's id to entity before save. #cakephp

<?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'];