Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session vs singleton pattern

I have a web application where I would like to pull user settings from a database and store them for Global access. Would it make more sense to store the data in a Singleton, or a Session object? What's the difference between the two?

Is it better to store the data as an object reference or break it up into value type objects (ints and strings)?

like image 281
chobo Avatar asked May 12 '10 19:05

chobo


3 Answers

Session. That's what it's for. The session is stored in the global cache (basically a singleton), keyed by the session id. That way, you get only the data for the session of interest. Using a singleton would basically be replicating the global cache and you'd have to reinvent the mechanism to retrieve data for each session independently.

Go ahead and store the object. Let the Session worry about serializing it to something that can be restored. Be careful, though, with what you put in the Session. You don't want to store too much data there or you'll use up a lot of memory (assuming an in-memory cache).

like image 158
tvanfosson Avatar answered Sep 22 '22 00:09

tvanfosson


Session object, definitely.

Singletons exist at the process level. This means that if you have 20 users accessing your site at any given moment, they're using the same singleton object. It's difficult to get used to this concept if you're not doing web development a lot.

Sessions exist at the user level. That means you can store data per user, not per process.

like image 27
Doug Avatar answered Sep 20 '22 00:09

Doug


If these settings will be used for all users of the site, put them in a singleton or in application cache. If they are specific to each user, put them in session.

Use object references when adding to app or session cache - I believe that value types will get boxed so they look like objects to the cache. If you use a singleton, it could go either way.

like image 20
Ray Avatar answered Sep 19 '22 00:09

Ray