Reputation: 625
$new = $this->memcache->get("posts");
if(empty($new)){
// Get the new posts
$new = Posts::getNow("10");
// Save them in memcache
$this->memcache->set('posts', serialize($new), 0, 60*3); // Cache time is 3 min
// If we found them in cache - load them from there
} else {
// Get data from memcache
$new = unserialize($this->memcache->get("posts"));
}
The code is very simple if there is data in cache load from there if is not to get them again. The interesting thing is sometimes when I view the site the div is empty and there is no data but when i reload the page there is. Is it possible my view of the site to be when the cache is being eraced ?
Upvotes: 0
Views: 1213
Reputation: 25938
That must be timing, you retrieve data from cache twice, once for checking it's here and second time for unserializing it. Data can be expired just between those calls and we have no control over it
Just unserialize the data you already got:
$data = $this->memcache->get("posts");
if(empty($data)){
// Get the new posts
$new = Posts::getNow("10");
// Save them in memcache
$this->memcache->set('posts', serialize($new), 0, 60*3);
} else {
// Unserialize data instead of retrieving it from cache for second time.
$new = unserialize($data);
}
Upvotes: 1