Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Caching Output in PHP

4.75/5 (4 votes)
22 Jan 2010CPOL 6.3K  
You can wrap the functions into a class and use the default class life cycle to your advantage.<?phpclass Cache{ const DIRECTORY = '../cache/'; const TIME = 600; protected $cache_directory; private $using_cached_file = false; public function __construct( $cache_directory =...
You can wrap the functions into a class and use the default class life cycle to your advantage.
<?php
class Cache
{
	const DIRECTORY = '../cache/';
	const TIME = 600;
	
	protected $cache_directory;
	
	private $using_cached_file = false;
	
	public function __construct( $cache_directory = null , $cache_time = null )
	{
		ob_start();
		$this->cache_directory = isset( $cache_directory ) ? ( is_string( $cache_directory ) ? $cache_directory : self::DIRECTORY ) : self::DIRECTORY;
		$cache_file = $this->get_cache_name();
		if ( file_exists( $cache_file ) && ( time() - ( isset( $cache_time ) ? ( is_int( $cache_time ) ? $cache_time : self::TIME ) : self::TIME ) < filemtime( $cache_file ) ) )
		{
			include( $cache_file );
			$this->using_cached_file = true;
			exit;
		}
	}

	public function __destruct()
	{
		if ( !$this->using_cached_file )
		{
			$file_buffer = fopen( $this->get_cache_name() , 'w' );
			fwrite( $file_buffer , ob_get_contents() );
			fclose( $file_buffer );
		}
		ob_end_flush();
	}

	protected function get_cache_name()
	{
		return $this->cache_directory . sha1( $_SERVER['REQUEST_URI'] ) . '.html';
	}
}
?>
Now using the code is even simpler:
new Cache();
At the top of each page.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)