Categories
PHP

Simple cache for PHP

Maybe not many of you already know that I had a dark side. Yes I was developing in ASP for long time……

I actually still like it, and because of that I like that much PHP (Well love it).

Everything is lot better in PHP, faster, updated, secure, easier…. But I was missing something that was really useful in ASP, the Application variables.

Thanks to leosingleton I found a solution but I modified in order to improve it.

Here you have this code to cache in disk variables 😉

First we need some defines:

define("APP_ACTIVE",true);//false disabled, true enabled the cache
define("APP_DATA_FILE",SITE_ROOT."/APP/application.data");//where we keep the cache, needs to be writeble
define("APP_EXPIRE",86400);//in seconds, when the cache expire, false is never deleted by time

This are the functions that makes this work:

////////////////////////////////////////////////////////////
function APP_start (){//load variables from the file
	if (APP_ACTIVE){
	    global $_APP;
	    if (file_exists(APP_DATA_FILE)){ // if data file exists, load the cached variables
	        $file = fopen(APP_DATA_FILE, "r");// read data file
	        if ($file){
	            $data = fread($file, filesize(APP_DATA_FILE));
	            fclose($file);
	        }
	        // build application variables from data file
	        $_APP = unserialize($data);
	    }
	    else  fopen(APP_DATA_FILE, "w");//if the file does not exist we create it

	    if (APP_DATA_FILE!=false){//if it's false we don't delete
		   //erase the APP every X minutes before loading next time
		    $app_time=filemtime(APP_DATA_FILE)+APP_EXPIRE;
		    if (time()>$app_time) unlink (APP_DATA_FILE);//erase the APP
	    }
	}
}
////////////////////////////////////////////////////////////
function APP_write(){//writes into the cache file
	if (APP_ACTIVE){
	    global $_APP;
	    $data = serialize($_APP); // write application data to file
	    $file = fopen(APP_DATA_FILE, "w");
	    if ($file){
	        fwrite($file, $data);
	        fclose($file);
	    }
	}
}

Usage:
We need to start the cache before you try to retrieve data:

APP_start();//starting values from the cache

Write data in the cache:

$_APP["var_name"]=$anyVariable
APP_write(); //we need to wirte every time we change values

Get value:

$anyVariable=$_APP["var_name"];

In $_APP[] you can keep as many variables as you want.

Notes:
-If you need to use $_APP in a function remember to make it global
-Only write when there’s changes in the vars
-Do not store lot of data, if not will make it really slow..
-Only start the APP once in the script
-Change the expire time on your needs
-The file stored in the disk should be only writable or readable by the server.