Accessing Session in Model

powtac picture powtac · Jan 4, 2012 · Viewed 20.5k times · Source

Is there a way of accessing the current session in the AppModel class?
I want to save the ID of the currently logged in user to almost every INSERT/UPDATE action.

Answer

powtac picture powtac · Jan 4, 2012

Found a working solution for CakePHP 2 here: Reading a session variable inside a behavior in cakephp 2

This is my AppModel:

<?php
class AppModel extends Model {

    public function beforeSave() {
        parent::beforeSave();

        if (isset($this->_schema['user_id'])) {

            // INSERT
            if (!strlen($this->id)) {

                App::uses('CakeSession', 'Model/Datasource');
                $user_id = CakeSession::read('Auth.User.id');

                $this->data[$this->alias]['user_id'] = $user_id;

            // UPDATE, don't change the user_id of the original creator.
            } else {
                unset($this->data[$this->alias]['user_id']);
            }
        }
        return true;
    } 
}