Simple caching in PHP5
class cache {
function __construct($path=’.') {
$this->path = $path;
}
function cache($name, $callback, $args) {
if (file_exists(“$this->path/$name”)) {
$this->callbacks[$name] = array($callback, $args);
return implode(”, file(“$this->path/$name”));
} else {
return $this->save($name, $callback, $args);
}
}
function save($name, $callback, $args) {
$text = call_user_func($callback, $args);
$fh = fopen(“$this->path/$name”, ‘w’);
fwrite($fh, $text);
fclose($fh);
return $text;
}
function __desctruct() {
if (is_array($this->callbacks)) {
foreach ($this->callbacks as $name => $callback) {
list($callback, $args) = $callback;
return $this->save($name, $callback, $args);
}
}
}
}
You call it using:
$cache = new Cache();
$cache->cache('MyFunc.txt', 'MyFunc', 'an argument');
All it does is save the output of the function to a file with the given name. The clever bit is that the output it sends to the browser is the content of the file; it doesn't actually call the function until the end of the script execution and so doesn't slow the output to the browser down.
Start sending output.
Output cached result of function.
Finish sending output.
Call function and save to the cache file.
It means the content will always be slightly out of date, but in a lot of situations that may not be a problem.
Quick note, this is only really possible (at least the way I've done it) in PHP5 because it requires destructor support.
Comments
No Comments on Simple caching in PHP5
-
Ashley furniture. on
Tue, 5th Feb 2008 9:17 pm
-
No teletrack payday loans. on
Sat, 9th Feb 2008 9:20 pm
-
No teletrack payday loans. on
Sat, 9th Feb 2008 9:20 pm
-
No teletrack payday loans. on
Sat, 9th Feb 2008 9:20 pm
-
No teletrack payday loans. on
Sat, 9th Feb 2008 9:20 pm
< ![CDATA[Lauren ashley furniture.
Ashley furniture. Ashley furniture huntington teak. Laura ashley furniture.]]>
< ![CDATA[Payday loans.
Payday loans. No fax payday loans. Laws about payday loans.]]>
< ![CDATA[Payday loans.
Payday loans. No fax payday loans. Laws about payday loans.]]>
< ![CDATA[Payday loans.
Payday loans. No fax payday loans. Laws about payday loans.]]>
< ![CDATA[Payday loans.
Payday loans. No fax payday loans. Laws about payday loans.]]>
