Information on how PHP developers can implement data caching to improve performance and scalability. Presented at the West Suburban Chicago PHP Meetup on February 7, 2008.
5. Where? Generally speaking... Local Database faster than Shared Database Local Disk faster than Database RAM faster than Disk
6. What? Anything you don't want to fetch or compute every time your code runs. Anything that isn't going to change very often.
7.
8.
9.
10. Caching On Disk Make a big array of the data you need. // At the start of your script $array = unserialize(file_get_contents($fileName)); // If the data isn't already there, put it there if(array_key_exists('key', $array)) { $value = $array['key']; } else { // Retrieve or compute $value $value = “Hello, World!”; $array['key'] = $value; } // At the end of your script file_put_contents($fileName, serialize($array));
11. Of Course, the OS Caches Files Modern operating systems use all your free RAM as a disk cache. If you read the same file over & over, it's probably being read out of RAM the second time on. So, it's usually ok to read a small file over & over.
12. memcached “ memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.”
13. memcached (It's a big array that doesn't go away when your PHP program ends.)
14. memcached <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die ("Could not connect"); $version = $memcache->getVersion(); echo "Server's version: ".$version."<br/>"; $tmp_object = new stdClass; $tmp_object->str_attr = 'test'; $tmp_object->int_attr = 123; $memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server"); echo "Store data in the cache (data will expire in 10 seconds)<br/>"; $get_result = $memcache->get('key'); echo "Data from the cache:<br/>"; var_dump($get_result); ?>
15. Caveats Be careful caching anything where security matters. Don't cache credit card info (PCI compliance) Keep cache up-to-date (when data changes)