1

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 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

u do not need unserialize data. cache_aadapters has config option to do it on the fly
2

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); } 

3 Comments

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:208 Stack trace:
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.
For avoid the Fatal error: Uncaught exception 'Zend_Cache_Exception' with message 'Invalid id or tag' You need to check if $key is valid name for cache: if (preg_match('/^[a-zA-Z0-9_]+$/', $load) > 0) { // load cache }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.