tags:

views:

1509

answers:

5

I've been working with sessions, MVC design and object oriented PHP. Where should I save or retrieve data from a session? I would like to retrieve it from within methods so I don't have to pass the data to the methods. Whats the best practice?

+1  A: 

I've tried it a few ways, including using a static wrapper class to handle it, but I always come back to just using the superglobal array by itself. I still use a wrapper for authentication checks and other repetitive tasks, but, ultimately, it's just easier and less verbose for me to use the stock setup.

Brian Warshaw
A: 

I think it is depend on the scope of where the retrived data will be used, if it is only used inside a method then why you should retrive it outside, and session is always available in superglobal variables it is better to localize it only when needed.

Ariel
+1  A: 

I typically put this inside the controller. It just makes sense.. The controller decides what happens and why not let it decide if people are allowed to do the requested actions. Typically you have multiple controllers in a MVC system. Eg. BaseController (abstract - common), NonSessionController extends BaseController (eg: used for static pages), SessionController extends BaseController (primary session handing here - this could be abstract). If you have for example different user types, you may want to polymorph this controller ones such as: AdminController, UserController, Etc.

DreamWerx
A: 

I wouldn't bother with session wrappers. You won't gain enough to merit the limitations. Going through the superglobal allows you to use any sort of (hopefully sane) data structure you want. My session data always ends up being 2 or more levels of array data, which is too tedious to manage through a session wrapper.

The superglobal doesn't even limit you from having PHP store your session data in a database using a save handler, which is quite nice for scalability.

alan szlosek
+3  A: 

Personally, I'm a huge fan of the Zend_Session wrapper class. I prefer to work with data in an object-oriented style and the namespacing advantage to using a wrapper is a huge plus.

Which of these looks better to you?

$_SESSION['Zend_Auth']['user'] = "myusername";

or

$authNamespace = new Zend_Session_Namespace('Zend_Auth');
$authNamespace->user = "myusername";

I prefer the look that using the accessors gives you.

Note: In an MVC system, no matter what method you choose, you should always be getting/setting session data in your controller.

leek