persisting session data

Hey guys,

Here’s the deal, I would like to to keep track of a user basket in session using Yii::$app->session. This works fine. But I would also like to save this basket and keep it persistent even after a user logout.

The difficult aspect here is that I would like to write to my DB/file/etc. only once before the session is destroyed, as opposed to each time the basket is altered (which would be easy enough to implement). Then when a session is opened I would like to set the basket to the previous value stored.

I’ve tried overriding yii\web\Session::open() and close() but this doesn’t seem to work because setting the basket on open() just seems to try and re-open a session and ends in an infinite loop.

So I’m at a loss, any help would be amazing. Or if you have other suggestions.

Best,

D

anyone?

Saving something in a session "when a user has logged out" is the wrong way to do this. Sessions, by definition, are temporary in nature. If you want to save a basket for a user, store it against the user eg, user_basket table. Then when a user logs in you can retrieve their last basket (and put it back into the session if necessary)

This is exactly what I want to do. The thing is I want to load the data from the database when the session is created and I want to save some of the session data when the session is destroyed. The idea being that I want these interactions with the database to be as minimal as possible so since sessions are persistant across multiple requests it seems like the correct way to go.

What I don’t want to do is save the data into the DB every time it changes. And this is what I’m struggling with.

I realize that there’s no guaranty the session will be programmatically destroyed but I would like to at least limit the loading into session to happen only when the session is loaded. That however doesn’t seem to be possible by overriding the session class. but maybe I’m wrong?

Best,

D