Skip to content

Instantly share code, notes, and snippets.

@vivirenremoto
Created August 25, 2011 02:49
Show Gist options
  • Save vivirenremoto/1169861 to your computer and use it in GitHub Desktop.
Save vivirenremoto/1169861 to your computer and use it in GitHub Desktop.
cache php class
<?php
class Cache{
public $path;
public $content;
public $life = 3600; // 1 hour
public $cache_path = 'cache/';
function get( $id ){
$this->id = $id;
$path = $this->getPath();
if( file_exists( $path ) && ( time() < ( filemtime( $path ) + $this->life ) ) ){
return file_get_contents( $path );
}
}
function start(){
ob_start();
}
function finish(){
$this->content = ob_get_contents();
ob_end_clean();
return $this->content;
}
function save(){
if( $this->id ){
$path = $this->getPath();
$handler = fopen( $path, 'w' );
fwrite( $handler, $this->content );
fclose( $handler );
}
}
function getPath(){
return $this->cache_path . $this->id;
}
}
// example 1: save page
// initialize
$cache = new Cache();
$cache->time = 3600;
$id = 'demo.htm';
$error = false;
// load cache
if( $content = $cache->get( $id ) ){
die( $content );
}
// start output buffering
$cache->start();
<html>
<head>
<title>example</title>
</head>
<body>
this code will be saved into cache
</body>
</html>
// show buffer
echo $cache->finish();
// no errors? save cache
if( !$error ) $cache->save();
// example 2: save variable
// initialize
$cache = new Cache();
$cache->time = 3600;
$id = 'demo.htm';
// load cache
$results = $cache->get( $id );
if( !$results ){
$results = $cache->content = 'some string';
$cache->save();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment