Apr
22

Zend Cache and Zend Feed Problem

Today I ran into a problem while caching feeds using Zend_Cache. I decided that I wanted to cache the returned object by the Zend_Feed. I had something like this:

$rssFeedLink = 'http://www.smooka.com/blog/';
$cacheId = 'rss_feed';

$frontendOptions = array(
		   	'lifetime' => 1800, // cache lifetime of 30 mins
		   	'automatic_serialization' => true);

$backendOptions = array(
		    	// Directory where to put the cache files
		    	'cache_dir' => '/cache/'
			);

// getting a Zend_Cache_Core object
$cache = Zend_Cache::factory('Core','File', $frontendOptions, $backendOptions);

if (!$rss = $cache->load($cacheId)) {
	try {
		$rss = Zend_Feed::import($rssFeedLink);
	} catch (Exception $e) {
		$feedError = true;
	}

	//check to see if it did not fail
	if (!$feedError && is_object($rss))
	{
		$cache->save($rss, $cacheId);
	}
}

//assuming that everything went right while fetching the feed
foreach ($rss as $item) {
	$channel['items'][] = array(
		'title'       => $item->title(),
		'link'        => $item->link(),
		'description' => $item->description()
	);
}


While iterating through the feed, the script would output the following message “Warning: Invalid argument supplied for foreach()”, under, “Zend/Feed/Element.php on line 322″ on an empty cache.

It appears that Zend_Feed and Zend_Cache do not get along, I’m pretty sure it’s a bug since it looks like Zend_Feed_Rss is sent to sleep by the $cache->save() call and it’s not waking up automatically. The solution that I found it’s pretty straight forward. Just modify the following piece of code.

if (!$feedError && is_object($rss))
{
	$cache->save($rss, $cacheId);
	//ADD a wakeup call to the RSS object
	$rss->__wakeup();
}

That should do the trick!

After I fixed the issue, I went back to the drawing board and decided that it was more efficient to cache the actual HTML output, instead of the returned object by Zend_Feed. That seems to work just fine, since the call to $cache->save() is done after the iteration of the feed items. That fixes the issue and at the same time you are eliminating the need to iterate and re-build the HTML every time the page is loaded.

Hope this information helps you, and if you have any questions or comments be sure to post them here.

3 Comments to “Zend Cache and Zend Feed Problem”

  • Cool post. Gonna keep this one in memory.

  • Did you find a workaround for the case where the feed fails to be downloaded (i.e. serving a cache of the failed output for 30 mins)?

    • Sorry but I have not experienced that problem.

Leave a comment