Welcome Guest, Not a member yet? Register   Sign In
Auth, sessions, fetching user data
#1

[eluser]Madmartigan1[/eluser]
What is the best way to deal with fetching data from a logged in user?

Here's my dilemma:

The Auth library I'm using has a function called user(), which is used for checking the logged in user's permissions, group, last name, etc. It's one of the most important functions.

I can store just the user id in the session, and query the database each time i want to fetch an item...
Code:
//results in 2 queries
echo 'Hello '.$this->auth->user()->first_name.' '.$this->auth->user()->last_name';

This way, if the user edits their name or an admin deactivates them while they are logged in, the changes will be effective immediately without doing anything to the session. The problem with this is I'm ending up with upwards of 20 identical queries per page load.

Another way would be to store the entire user object in the session, and then simply fetch items from the session. Session data could be repopulated if the user edits something. This would result in very few queries but be less accurate and arguably less secure.


Goal:

I would like to be able to query the database ONCE per page load, fetch the user's data, and use it for each future request. Each new page load would require another query to re-check the user's data.

Code:
class Auth {

    function user()
    {
        //if a query on the user was run
            //return saved result
        //else
            //query the database
            //save the result  (i think i tried flashdata but failed)

        //return the user object
    }

}

I am open to all suggestions and discussion about these methods as this is the first time I've really gotten into writing an auth library. I feel like there is something very basic that I'm missing here. Thanks for reading Smile
#2

[eluser]WanWizard[/eluser]
I have a last_updated timestamp in all my records (I use Datamapper, which automatically updates this column on save). This makes it easy to check if something has changed when I read a record.
I also use Phil Sturgeon's caching library, to cache indivudual query results. When a user or permission record is updated, the cache file is deleted.

I store only the key information in the session. On every page load, I load the cached user data, and if not present I call the model that fetches all data (and repopulates the cache).
#3

[eluser]Madmartigan1[/eluser]
Thanks for the reply.

I was able to achieve my goal by setting a class variable 'user' in the constructor of the Auth library. For now, the function user() just returns the value of that variable. Now, only the user id is stored in the session, and a new query on the user is run once each page load. Seems perfectly simple and acceptable to me unless I'm being dense (I have been up very very late tonight!).

Thanks again. I have ORM-phobia atm, but DataMapper looks quite good!




Theme © iAndrew 2016 - Forum software by © MyBB