Click here to Skip to main content
15,884,628 members
Articles / Programming Languages / PHP
Alternative
Tip/Trick

Caching Output in PHP

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
22 Jan 2010CPOL 6.2K   3  
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)


Written By
Software Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --