> I'm building a web application that has a User perl module.  I have
several other perl modules that need to know the user id of the current
logged in user (or 0 for a guest user).  I was thinking that I could write
the User class in such a way that every time (except the first) a
constructor was called the same instance of the user object would be
returned for each apache request.
>
> Is this the best way to go about solving my problem?  If so what's the
best way to implement this?  Or maybe I should just pass around the user id
to every class?  I'd perfer to avoid this if possible.

Try this:

sub get_user {
    my $user = Apache->request()->pnotes('USER');
    if (!$user) {
        # first time for this request
        $user = MySite::User->new(); # or whatever
        Apache->request()->pnotes('USER', $user);
    }
    return $user;
}

Put it in some utility class that your other classes all use.
Alternatively, you could make your User class cache itself in pnotes and
just have everyone call new(), but that assumes you'll never want to use it
outside of mod_perl.  Also see Class::Singleton.

- Perrin

Reply via email to