View Full Version : Session Wrapper Class?
08-27-2009, 02:15 PM
I've been developing in PHP for a long time now, but never really looked too closely into sessions. I can create login scripts and whatever, then set session variables and use those throughout, but I'm just not that confident because I've never felt like I learned the right way to use them.
I'm looking for any tips about using sessions in general (or tutorials), as well as information on using a session wrapper class. I've seen a few but I'm unsure as to whether or not I really need them or should be using one.
I'm not sure what you mean by a "session wrapper class".
Certainly though, I use wrapper classes to hide all the superglobals.
Strictly speaking, it is bad coding practice to use $_SESSION directly in a script.
I tend to use a singleton class to access $_SESSION.
Look up "php singleton" and think about how you would like to use that to wrap up $_SESSION. (there are various solutions, its best to chose the one that you prefer).
Using a wrapper class like that can be very useful for portability, avoiding race hazards in multi-threaded applications, etc, etc.
08-28-2009, 02:45 PM
When I say "session wrapper", I mean something like this:
Then, instead of accessing $_SESSION, you instantiate an instance of the Session class to do all of your session handling. The example I provided is a simple one, but there are Session wrappers out there that do a whole lot more crap - notably giving you some sort of additional control over how long the session will last as well as checking to see if the session is expired every time session_start() is called.
I do see that a singleton (or single instance of the class) would be useful - it doesn't make sense to create a bunch of Session objects that all do the same thing. Good object-oriented design says one is enough and to use that one throughout.
Do you recommend a wrapper class with the added functionality, or just a simple wrapper that extends the default session functionality to me through a static object?
Oh, and while we're on the topic, is there an advantage to using a singleton over just making it global? Right now I'm doing that with a database class...no singleton needed, yet I keep just one copy of that class. After all, the end effect is really the same.
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.