Reputation: 505
I have a problem right now where, when a user logs in, their user object is stored in a session variable as to be quicker than making a database call each time. The problem I am having is if something updates on their end (like the number of points they have), I have no way to modify that session variable, I can only update their row in the table.
Is there any way for php to access that session variable given it's unique identifier instead of reading from their cookie? Or would it be better to check some flag in the database, and if the flag is set, update all the information?
Upvotes: 0
Views: 303
Reputation: 20601
You need to read it from a centralized storage (contrary to sessions). If you could, you should avoid the database calls. Use cache and update the cache on insert:
then we're done, let's try the loop again:
We're saving really many database calls here.
Some possible engines for caching are:
If you're on shared hosting, or unable to get PHP compiled with a good engine for caching, writing to files could do the job.
Upvotes: 2
Reputation: 13756
What I suggest is to create custom object which will hold data for example 5 minutes and than it will be reloaded. Just create object which will load your data from session, if loaded object is older than five minutes just reload data.
I think this can resolve your problem
class MySession
{
public $Duration = 0;
public $Loaded = 0;
public static function Load()
{
$obj = null;
if(isset($_SESSION["my_session"]))
{
$obj = deserialize($_SESSION["my_session"]);
if((time()-$obj->Loaded)>$Duaration)
$obj = self::LoadObject();
}
else { $obj = self::LoadObject(); }
$obj->Save();
return $obj;
}
public function Save()
{
$_SESSION["my_session"] = serialize($this);
}
public static function LoadObject()
{
$obj = new MySession();
$obj->Loaded = time();
//logic for updating data
return $obj;
}
}
Upvotes: 1