I currently have an Audtiable Behavior that inserts into an audits table for each CRUD operation. One of the key pieces of information I want to store into the audits table is the user id. How do I access the user id of the currently logged in user in the behavior class? What is the best approach?
Thatās incorrect, as it brakes MVC, is hard-coding etc etc.
You can do it in two ways, using cakeās event system :
hacky way :
add to config/boostrap.php
\Cake\Event\EventManager::instance()->on(āModel.initializeā, function (\Cake\Event\Event event) {
if (isset(_SESSION[āuser_idā])) { event->subject()->userId = _SESSION[āuser_idā];
}
});
more proper way :
in AppController file, after top line that starts with ānamespaceā
add :
use Cake\Core\Configure;
use Cake\Event\EventManager;
finally in the class modify/add beforeFilter() callback so it will look like :
public function beforeFilter(Event $event)
{
EventManager::instance()->on('Model.initialize', function (Event $event) {
if ($this->request->session()->check('user_id')) {
$event->subject()->userId = $this->request->session()->read('user_id');
}
});
parent::beforeFilter($event);
}
From now every model will contain userId property (if it was set in session prior to model initialization) , and from behavior you can access model to which it is attached to, or you can load some model.