Session Object

Reading and writing values out of the session object is pretty straightforward. But what if you want to store an entire object in there? A common example would be to store user information when logged in.

One way to pull out just one property would be to assign the user object back into a variable and grab the fields from there.

$userinfo = $this->Session->read('User');
echo $userinfo['id'];

I figured there'd be an easier way but the documentation didn't reveal anything so I tried using the forward slash just like you would in the model. read('User/id') didn't work. I snooped around the code and noticed it uses the period as a separator. Therefore, instead of the above example, you could do the following:

echo $this->Session->read('User.id');
Published July 25, 2006 · Updated July 25, 2006
Categorized as CakePHP
Short URL: https://snook.ca/s/689

Conversation

3 Comments · RSS feed
Jim Zaghini said on December 29, 2006

You have just saved me on a half-related issue. I've been stuck on it for the last 4 hours...

Thankyou!

Paul (WebbedIT) said on December 13, 2008

Hi, what would be the load implications of using $this->Session->read('User.id'); multiple times in a controller action over creating a local variable/array and accessing that?

I am a self-taught PHP/MySQL developer with 6 years of bad habits from never working as part of a development team. For the last 4 weeks I have been evaluating CakePHP by recoding and structuring of of my bigger client applications and I feel as though a light has been switched on with regards to the use of the MVC design pattern and naming conventions.

However, spending all my time over the last 6 years making things work and not enough time on making sure they are secure and optimised, I have no idea on the impact of using functional wrappers such as the one above so at present I have been using $this->session_read(); once in an action and writing it to a local variable/array if I want to access the value more than once.

P.S. I love the design and layout of this site .. kudos!

Jonathan Snook said on December 13, 2008

@Paul: There's going to be some overhead, regardless since the User.id needs to be parsed but it's fairly minor. If you plan to use it repeatedly, it's probably easier to store that information in a variable. Save yourself some typing and the extra lookup.

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.