I prefer a random file, watch how this caching class is written from opencart:
<?php final class Cache { private $expire = 3600; public function __construct() { $files = glob(DIR_CACHE . 'cache.*'); if ($files) { foreach ($files as $file) { $time = substr(strrchr($file, '.'), 1); if ($time < time()) { unlink($file); } } } } public function get($key) { $files = glob(DIR_CACHE . 'cache.' . $key . '.*'); if ($files) { foreach ($files as $file) { $handle = fopen($file, 'r'); $cache = fread($handle, filesize($file)); fclose($handle); return unserialize($cache); } } } public function set($key, $value) { $this->delete($key); $file = DIR_CACHE . 'cache.' . $key . '.' . (time() + $this->expire); $handle = fopen($file, 'w'); fwrite($handle, serialize($value)); fclose($handle); } public function delete($key) { $files = glob(DIR_CACHE . 'cache.' . $key . '.*'); if ($files) { foreach ($files as $file) { unlink($file); } } } } ?>
really easy to use and it works so well, you use a random request and save your data in a file, I am sending an example.
$cache = new cache(); $data = $cache->get('my_query_key'); if (!$data) { // I do my query and I put it into an array (because I can use shuffle :P) $result = mysql_query('SELECT * FROM items'); $data = array(); while($row = mysql_fetch_assoc($result)) { $data[] = $row; } $cache->set('my_query_key', $data); } shuffle($data);
The only thing that may occur when saving more than 100 kilobytes of file, but, as rumor has it, I use it and work fine so that I have no problems. Ah .. in this case you do not need to use RAND () to query .: P
I am writing this message without checking sintax, be ware ^^
Paper bat
source share