<?php
class FileCache {
private $id;
private $map = array();
private $filecache_dir = 'cache/';
private $filecache_lifetime = 5; // время кэширования в секундах
function FileCache($id) {
$this->id = $id;
}
function get($code) {
$key = md5($code);
$filename = $this->filecache_dir . $this->id . '-' . $key;
if (file_exists($filename)) {
$filestat = (stat($filename));
$timestamp = $filestat[9];
if (time() - $timestamp > $this->filecache_lifetime) {
echo "[SRCEXP] ";
return $this->put($filename, $code);
} else {
echo "[CACHED] ";
return file_get_contents($filename);
}
} else {
echo "[SRCNEW] ";
return $this->put($filename, $code);
}
}
function put($filename, $code) {
$value = $this->run($code);
file_put_contents($filename, $value);
return $value;
}
function run($code) {
$func = create_function('', "return $code;");
return $func();
}
}
// тестовая функция выполняющая "тяжёлую" операцию
function test($filename) { return sha1(file_get_contents($filename)); }
// запуск теста
function test_run($usecache) {
$fc = new FileCache('test');
$start_time = microtime(1);
for ($i = 1; $i <= 30; $i++) { // test iterations
$n = rand(1,30); // random file
$start_step_time = microtime(1);
// вызываем тестовую функцию
if ($usecache)
$fc->get("test('data/' . $n)"); // с кэшированием
else
test('data/' . $n); // без кэширования
echo sprintf("Step: %s; File: %s; Time: %f (%f); ", $i, $n, microtime(1) - $start_step_time, microtime(1) - $start_time);
}
echo '<hr>Total time: ' . (microtime(1) - $start_time) . '<br>';
}
// тест без кэша
echo '<h1>Direct read</h1>';
test_run(0);
// тест с кэшем
echo '<h1>Cached read</h1>';
test_run(1);