Question

I have a User object that, upon successful authentication, is tucked into the session (sans security info) for easy recall and for determining whether we have an authenticated user or anonymous session. There are several paths by which the user can alter some or all of his or her information and I'd like to keep that session value up to date. The obvious answer is to update the value in the afterSave() callback, but that, of course, violates MVC.

Is there another way of capturing every change in one place so that I don't have to drop session writes all over the place? I can't think of anything, nor have I been able to find any other ideas. Am I the only person trying to do something like this?

Thanks.

Final Solution: I marked neilcrookes' response as the answer, frankly, because there doesn't seem to be the better way. Since this way violates my OCD senses, though, I took a slightly different path. I decided to have my User::authenticate() method return the authenticated user object to the caller so it can do whatever it wants with it. One of the things that the callers "want" to do is to drop that value in the session. It's redundancy, but it's very, very limited. In my mind, that felt better than accessing the session from the model (though it's certainly a damned if you do, damned if you don't scenario).

Was it helpful?

Solution

Some might disagree but I'd screw MVC, do it in Model::afterSave() and use $_SESSION - test for the session before writing to it, in case it's not started for example you are saving against the model in a shell or something.

MVC is a general pattern - a guideline, you can bang your head against it trying to figure out how to achieve something that doesn't quite fit, or just do it another way and move onto to something more important.

Bring on the flames.

OTHER TIPS

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

after save

Use Like this

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

You should be able to just use AppController to create the necessary callback(s) that keep your session data up to date. So, for instance, you could have your User model afterSave() set a property called changed to true. Then in your AppController->afterFilter() you check that property and update the session data as necessary.

Alternatively, you could write a component through which to update your user info and also your session data. Then any controller that needs to change user info just needs to include that component.

There's no need to write redundant code or break MVC.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top