Sunday, September 30, 2012

Ceating Page Cache


<?php
/**
* @Author: Rbernal
* @ 11-13-09
* @ page caching
*/

class PageCache{
    
    /**
     * @ path where we save or cache files
     */
    private $cache_path;
    
    /**
     * @ page information basename and the dir
     */
    private $page_info;
    
    /**
     * @ file content to be saved on a as cache files
     */
    private $page_content;
    
    
    /**
     * @ file content to be saved on a as cache files
     */
    public $use_cache = true;
    
    
    /**
     * @ constructor
     */
    public function __construct( $base_path = '/' )
    {
        $this->cache_path = $base_path;
        $this->getPageInfo();
        $this->createDirectory();
    }
    
    
    /**
     * @ set page information
     */
    private function getPageInfo()
    {   
        $this-> page_info = pathinfo( $_SERVER['REQUEST_URI'] );
        $this-> page_info['dirname'] = substr($this-> page_info['dirname'],1).'/';
    }
    
    
    /**
     * @ create directory if Directory does not exist
     */
    private function createDirectory()
    {
        $this->cache_path = $this->cache_path.$this-> page_info['dirname'];
        if( !file_exists($this->cache_path)  ){  
            mkdir($this->cache_path, 0777, true);
        }
        
    }
    
    
    /**
     * @start reading the page for caching
     */
    public function startCache()
    {
        ob_start();
    }
    
    
    /**
     * @limit the output buffer and save
     */
    public function endCache()
    {
        $this->page_content = ob_get_contents();
        $this->saveCache();
    }
    
    
    /**
     * @remove output buffer
     */
    private function clean()
    {
        ob_clean();
    }
    
    
    /**
     * @save cache file if not exist
     */
    private function saveCache()
    {
        $file = $this->cache_path.md5($_SERVER['REQUEST_URI']);
        if( !file_exists($file) &&  $this -> use_cache )
        {  
             file_put_contents($file, $this->page_content);
        }
        
    }
    
}
?>