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.
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;
}
}
$this->Session->write('Auth.User.jwt', $jwt);
to CakeSession::write('Auth.User.jwt', $jwt);
to get my code working from Controller to Model. –
Toaster In CakePHP 2.x you can use AuthComponent statically and get the logged in user's ID in the model like this:
$userId = AuthComponent::user('id');
If you are calling saves from a controller, you could just include the session data in the data that you assign to your model before the save:
$data['ModelName']['session_id'] = $this->Session->id;
$this->ModelName->save($data);
Or you could create a variable in your model and store the ID there for use later:
<?php
//in model
class MyModel extends AppModel{
public $session_id;
}
//in controller
$this->MyModel->session_id = $this->Session->id;
?>
If you must use the component in your model, then you may be able to load it. I'm not sure if this will work though. This is not good practice and you should probably consider doing it a different way.
<?php
App::uses('CakeSession', 'Model/Datasource');
class MyModel extends AppModel{
public function beforeSave(){
$this->data['session_id'] = $this->Session->id;
return true;
}
}
?>
For 3.6 and above, to access current Session from Table class use Cake\Http\Session
use Cake\Http\Session;
class UsersTable extends Table
{
/**
* Get user from session
*
* @return object
*/
public function getUser()
{
$id = (new Session())->read('Auth.User.id');
$user = TableRegistry::getTableLocator()
->get('Users')
->findById($id)
->first();
return $user;
}
}
Source: https://api.cakephp.org/3.6/class-Cake.Http.Session.html#_read
© 2022 - 2024 — McMap. All rights reserved.