views:

287

answers:

2

How can i do the followin tasks

public function addToCache($id,$items)
{
 // in zend cache
}

public function getFromCache($id)
{
 // in zend cache
}

The first method should take an id and items which should be cached.

The second method should just take an id of an cached object, and should return the content of the cache of that item id.

i want to be able to do something like that;

public function getItems()
{
   if(!$this->cache->getFromCache('items'))
   {
       $this->addToCache('items',$this->feeds->items());
       return $this->cache->getFromCache('items');
   }

}

How can i do the both methods in zend cache ?

+2  A: 

Assuming that you have already set up an instance of Zend_Cache and have access to it through a local variable $this->cache, your functions would be implemented as:

function getFromCache($key) { return $this->cache->load($key); }
function addToCache($key,$value) { $this->cache->save($key,$value); }
Victor Nicollet
thank you very much i will test it right now ;-)
streetparade
hmm.. i got this Fatal error: Uncaught exception 'Zend_Cache_Exception' with message 'Invalid id or tag : must be a string' in /var/www/inc/Zend/Cache.php:208Stack trace:
streetparade
As far as I can remember, the key is expected to be a string. If you wish to provide anything else, you should convert it to string.
Victor Nicollet
+2  A: 

Everything to get started is in the Zend docs. You do have to dig in a little and get comfortable, it's not a "quick how do I do this" type of area.

But, the general cache-check looks like this:

$cache = /*cache object*/
if ( !($my_object = unserialize($cache->load('cache_key'))) ) {
  $my_object = /*not found so initialize your object*/
  $cache->save(serialize($my_object)); // magically remembers the above 'cache_key'
}

$my_object->carryOnAsIfNothingStrangeJustHappenedThere();
Derek Illchuk
u do not need `unserialize` data. `cache_aadapters` has config option to do it on the fly
SM