13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

848 Chapter 33 Connecting to <strong>Web</strong> Services with XML <strong>and</strong> SOAP<br />

Listing 33.12<br />

Continued<br />

}<br />

// is cached data missing or > 1 hour old?<br />

if(!file_exists($filename) ||<br />

((mktime() - filemtime($filename)) > 60*60)) {<br />

return false;<br />

}<br />

$data = file_get_contents($filename);<br />

return unserialize($data);<br />

}<br />

// add Amazon data to the cache<br />

function cache($type, $parameters, $data) {<br />

if($type == 'browse') {<br />

$filename = CACHE.'/browse.'.$parameters['browsenode'].'.'<br />

.$parameters['page'].'.'.$parameters['mode'].'.dat';<br />

}<br />

if($type == 'search') {<br />

$filename = CACHE.'/search.'.$parameters['search'].'.'<br />

.$parameters['page'].'.'.$parameters['mode'].'.dat';<br />

}<br />

if($type == 'asin') {<br />

$filename = CACHE.'/asin.'.$parameters['asin'].'.'<br />

.$parameters['mode'].'.dat';<br />

}<br />

$data = serialize($data);<br />

$fp = fopen($filename, 'wb');<br />

if(!$fp || (fwrite($fp, $data)==-1)) {<br />

echo ('Error, could not store cache file');<br />

}<br />

fclose($fp);<br />

Looking through this code, you can see that cache files are stored under a filename that<br />

consists of the type of query followed by the query parameters.The cache() function<br />

stores results by serializing them, <strong>and</strong> the cached() function deserializes them.The<br />

cached() function will also overwrite any data more than an hour old, as per the terms<br />

<strong>and</strong> conditions.<br />

The function serialize() turns stored program data into a string that can be stored.<br />

In this case, you create a storable representation of an AmazonResultSet object. Calling<br />

unserialize() does the opposite, turning the stored version back into a data structure

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!