Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

Caching Output in PHP

, 22 Jan 2010
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

fly904
Software Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 22 Jan 2010
Article Copyright 2010 by fly904
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid