Jump to content

[SOLVED] Reinitiating user class


matthewhaworth

Recommended Posts

For a while now I've been creating user objects on every page load and filling them with session data about the user i.e. $_SESSION['user']['name'].. now instead, I want to keep the user details in the object, and pass the object through sessions.. but I'm having a bit of a problem with doing that. Do I check to see if a user object already exists on every page? Or do I check it within the user object's constructor?.. but then again.. I shouldn't have constructed the user object if one already exists.. so in that case, the constructor should never run. So it'll have to check if the user object exists, and if not, create one?

Another problem I'm having is, I believe objects don't save data when passed through sessions and that you have to somehow, recreate it through __wakeup.. how would I go about that?

 

Edit:

I figure something like

 

<?php
if(!is_object($_SESSION['user']))
{
    $_SESSION['user'] = new user;
}
?>

 

Would work?

 

Link to comment
Share on other sites

It would work. May want to put in a isset for good form. You probably don't need __wakeup(). Only when you have a unserializable property value, like a file- or database handle. You shouldn't have that in a "user" object.

 

Another option would be to use a Factory Method in the User class.

 

public static function factory()
{
    if(!isset($_SESSION['user']) || !$_SESSION['user'])
    {
        $_SESSION['user'] = new self;
    }
    return $_SESSION['user'];
}

 

This makes it a Singleton though, so may want to declare the constructor private.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.