0
    $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 ?

Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93
Marian Petrov
  • 625
  • 2
  • 9
  • 21

1 Answers1

1

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);
}
Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93
  • Another question : How to unset variables which are not being used ? And how to know which are not being used ? – Marian Petrov Jun 20 '12 at 12:37
  • @MarianPetrov, look at [php - what's the benefit of unsetting variables?](http://stackoverflow.com/questions/5030600/php-whats-the-benefit-of-unsetting-variables?lq=1) and linked questions for more details on that. – Juicy Scripter Jun 20 '12 at 12:44