CakePHP: update session variable after saving

I have a User object that, after successful authentication, is refueled into the session (without security information) for easy calling and to determine if we have an authenticated user or an anonymous session. There are several ways in which a user can change some or all of his or her information, and I would like to keep this session current. The obvious answer is updating the value in the afterSave() callback, but that of course violates MVC.

Is there any other way to capture each change in one place, so I don’t need to record the session in all places? I cannot think of anything, and I could not find any other ideas. Am I the only person trying to do something like this?

Thanks.

The final decision . I marked Neilcrookes answer as an answer, to be honest, because it doesn't seem to be the best way. Since this method violates my OCD feelings, though, I took a slightly different path. I decided that my User::authenticate() method returns an authenticated user object to the caller so that he can do whatever he wants with it. One of the things that users want to do is to discard this value in the session. This is redundancy, but it is very, very limited. In my opinion, it was better than accessing a session from a model (although it is, of course, damned if you do, damned if you don't have a script).

+4
source share
4 answers

Some may disagree, but I would screw MVC, do it in Model :: afterSave () and use the test $ _SESSION for the session before recording it if it is not running, for example, you save against the model in the shell or something.

MVC is a common template - a guide, you can bang your head about it, trying to figure out how to achieve something that doesn't quite fit, or just do it differently and move on to something more important.

Bring the fire.

+4
source
 //in users controller if ($this->User->save()) { $this->Auth->login($this->User->read()); $this->Session->setFlash[.. etc] 

And for the record, I do not agree with the answer of neilcrooks, but I will refrain from feeding the troll.

+8
source

after saving

Use like this

 $this->Session->write('Auth.User.mmid', $kinde['Kindle']['id']); 
+1
source

You can simply use the AppController to create the necessary callbacks that let you update session data. So, for example, you could use the User model afterSave() for the changed property for true. Then in AppController->afterFilter() you check this property and update the session data as needed.

Alternatively, you can write a component with which you can update user information, as well as session data. Then any controller that needs to change user information should simply enable this component.

No need to write redundant code or interrupt MVC.

-1
source

Source: https://habr.com/ru/post/1285911/


All Articles