Access user id within Audit Behavior

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?

Thanks

Jason

It looks like you can use the built in $_SESSION variable and this works.

That’s incorrect, as it brakes MVC, is hard-coding etc etc.

You can do it in two ways, using cake’s event system :

  1. 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ā€];
    }
    });

  2. 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.

1 Like

oh okay Thank You I will give this a try