It's an asymmetric world

Coredumps from Jesus Castagnetto's brain

  • Increase font size
  • Default font size
  • Decrease font size
Error
  • Error loading feed data.


CachedTemplate: A generalized template caching class - Class CachedTemplate (public methods)

E-mail Print PDF

Public Methods:

set_cache_dir
Prototype:
void set_cache_dir (string $dir)
Description:
Sets the directory to be used for caching parsed documents
Example:
	// Set the caching directory to "../mycachedir"
$obj = new CachedTemplate();
$obj->set_cache_dir("../mycachedir");

 

set_cache_length
Prototype:
void set_cache_length (int $length)
Description:
Sets the maximum length (in time units) to keep cached documents
Example:
	// Set the caching length to 12 hours
$obj->set_cache_length(12);
$obj->set_time_unit("hour");
set_time_unit
Prototype:
void set_time_unit (string $tunit)
Description:
Sets the time unit to be used for calculating the lifetime of a cached document. Valid units are: "sec", "min", "hour", "day"; if and invalid unit is used, it defaults to "day".
use_get
Prototype:
void use_get ([string $how])
Description:
Calls the method use_vars to use the contents of the $QUERY_STRING global variable for cache writing, reading and validation. The default value of the the parameter is "in_name", i.e. use the $QUERY_STRING when generating a unique name for the cache file. See the examples in the files get_example1.php and get_example2.php for more information.
Note: This method has to be used before the validation methods.
Example:
Assuming that the script mypage.php was called using the URL: http://www.mysite.com/path/to/mypage.php?somevar=simple, we can use the query string as part of the name of the cached file, so if we pass other values, e.g. somevar=notsimple, a cached file will be created for each instance.
	$tpl = new CachedTemplate();
$tpl->init();

// use the query string for generating the names of the cache files
// which is the default behavior, and equivalent to using
// $tpl->use_get("in_name");
$tpl->use_get();
...
In case you prefer not to append the GET query string to the name of the cached file, then you can store it for comparison purposes:
	...
$tpl->use_get("store");
...
use_vars
Prototype:
void use_vars ([mixed $vars, string $how])
Description:
Sets the variable flag $USEVARS and sets the appropriate value for the $VARSVAL variable. This method accepts as a first parameter either the string "QUERY_STRING" (when using the variables passed in a GET query string), or an array of variable names and values to be used in the writing, reading and validation of the cached files. The default values for the parameters are "QUERY_STRING" and "in_name" respectively. Valid values for $how are: "in_name" (default) and "store".
Note: This method has to be used before the validation methods.
Example:
We will want to use some important values to generate unique cache filenames:
	$tpl = new CachedTemplate();
$tpl->init();

$important_vars = array(
"theme" => "simple",
"fgcolor" => "black",
"bgcolor" => "white"
);

$tpl->use_vars($important_vars, "in_name");
...
If you are using PHP4, you can use the compact function to generate the array needed. In the example below, we also decide to store the variables into a *.vars file, which will be used during validation:
	...
// assuming $theme, $fgcolor and $bgcolor have been defined
$important_vars = compact($theme, $fgcolor, $bgcolor);

$tpl->use_vars($important_vars, "store");
...
write_to_cache
Prototype:
void write_to_cache (string $data [, string $datacheck, string $filename])
Description:
Writes the parsed data to a cache file, and generates an associated control file containing a creation timestamp, the length of time to cache the information, and the unit of time used. If the second parameter is present, it will included in the control file to be used for external data validation (see: is_data_valid). If the third parameter is present, this will be the name used for the cache and control files, otherwise the method will use the filename stored in $PHP_SELF, replacing all "/" characters with "_".
Example:
	// write parsed document to files "coolfile.parsed.cntrl"
// and "coolfile.parsed.cache", using today's timestamp
// as data validation parameter
$data = $obj->getParsedDoc();
$obj->write_to_cache($data, time(), "coolfile.parsed");
read_from_cache
Prototype:
boolean read_from_cache ([string $filename])
Description:
Reads the cached file from the cache directory and sends it to the standard output, returns true on success, false otherwise. If a parameter is passed, it will be used as the name for the cached file.
Example:
	// read the current document from cache
$obj->read_from_cache();
get_from_cache
Prototype:
string get_from_cache ([string $filename])
Description:
Reads the cached file from the cache directory and returns it as a string if succesful, an empty string otherwise. If a parameter is passed, it will be used as the name for the cached file.
Example:
	// get a cached block in this document
$header = $obj->get_from_cache("header_".$PHP_SELF);
is_cached
Prototype:
boolean is_cached (string $filename)
Description:
Returns true if the file $filename is cached, false otherwise.
Example:
	if ($obj->is_cached("coolfile.parsed")) {
// do something
}
valid_cache_file
Prototype:
boolean valid_cache_file ([string $filename])
Description:
Returns true if it finds a valid cache file, false otherwise. If the parameter $filename is omitted, then the variable $PHP_SELF with the "/"s replaced by "_"s will be used.

The algorithm to decide whether a cached file is valid is:
  1. If a cached file exists (uses method is_cached) go to the next step, otherwise return false and exit method.
  2. Is the variable $USEVARS set?
    • No - then go to the next step
    • Yes - then check how do we have to use it, if the value of $USEVARS is:
      • "in_name" - apply URL encoding to $VARSVAL and append it to the filename for the cache and control files, then go to the next step (this is done by calling the method _gen_filename)
      • "store" - read the stored $VARSVAL from the *.vars file and compare with the current one, return false if they are different, otherwise go to the next step
  3. Get the creation timestamp, time length and time unit from the control file. If it is an invalid time unit return false, otherwise go to the next step.
  4. Get the list (if any) of templates included in the document. Loop through the list and return false if any of the templates does not exist, or has been changed since the cached file was created (use the the creation timestamp obtained in the previous step), otherwise go to the next step.
  5. Finally, compare the creation timestamp with the current one, and determine if the cached file content have expired (return false) or not (return true).
Example:
	if ($obj->valid_cache_file()) {
echo $obj->read_from_cache();
} else {
// parse the document and save into cache
}
is_data_valid
Prototype:
boolean is_data_valid (string $datacheck[, string $type, string $filename]
Description:
Used to determine if the data from an external source has changed since the cache file was last created. It expects the first parameter to be either a unix timestamp or an md5 hash of the data. The second parameter should be either "timestamp" or "md5", it defaults to "timestamp". The third parameter (if present), should be the name used to generate the cached files.

The idea behind using this method is, to allow for cached data regeneration when the data contained there changes in the original source, i.e. if you are pulling the body of a page from a database, and the information in the database changes, you can use the timestamp of the changed row to decide if the page needs to be reparsed. Similar approach can be done using an md5 hash of the data, which should also detect changes in it, this is for cases in which a timestamp is not feasible.
Example
In the following example, we extract information from a database of news articles, so we need to check if the cached information is up to date, we use the field ts which contains a MySQL timestamp, and we ask for the corresponding unix timestamp:
	...
$link = mysql_pconnect();
mysql_select_db("documents");
$query = "select UNIX_TIMESTAMP(ts) from news where topic='science' ";
$query .= "and subtopic='compchem' order by ts DESC limit 1";
$res = mysql_query($query, $link);
list($datats) = mysql_fetch_row($res);

$tpl = new CachedTemplate();
if ($tpl->valid_cache_file() && $tpl->is_data_valid($datats, "timestamp")) {
// cached info valid, send it to the user
} else {
// parse the document
}
...
A similar approach can be done with data coming from files, etc. See also the files datavalid_example1.php and datavalid_example2.php.

 

set_use_lock()
Prototype:
void set_use_lock (void)
Description:
Activates the use of locking while reading/writing cache files
Example:
	// use locking while processing cache files
$obj->set_use_lock();
unset_use_lock()
Prototype:
void unset_use_lock (void)
Description:
Deactivates the use of locking while reading/writing cache files
Example:
	// do not use locking while processing cache files
$obj->unset_use_lock();
is_locked()
Prototype:
boolean is_locked (string 4filename)
Description:
Returns true if file lock exists, false otherwise
Example:
	if ($obj->is_locked("mycachefilename")) {
// then do something;
} else {
// proceed as always
}
mk_lock()
Prototype:
boolean mk_locked (string 4filename)
Description:
Creates a lock file if one does not already exists, returning true if succesful, false otherwise
Example:
	if ($obj->mk_lock("mycachefilename"))
// then we can manipulate the cache file
} else {
// other process is locking the cache file, we need to wait
}
rm_lock()
Prototype:
boolean rm_locked (string 4filename)
Description:
Removes a lock file if one already exists, returning true if succesful, false otherwise
Example:
	// clean old lock files
if ($obj->is_locked("mycachefilename"))
$obj->rm_lock("mycachedfilename");
}
utime
Prototype:
int utime (void)
Description:
Returns timestamp including microseconds. Shamelessly *borrowed* from CDI's FastTemplate class
Example:
	$start = utime();
// after some code
$end = utime();
echo "Processing took: ".($end - $start) * 1000." millisecondsn";


 

Our son is here!

Our son Daniel Ken was born on March 09, 2009 at 14:39 PET (UTC - 5). We are happier than we've ever been in our lives.

Now the real work begins, helping a new life develop into this world.

-- Mom and Dad

My son's Blog

My Random Photo

From Airin's Photo Gallery

Green Hosting at Dreamhost.com

Visitors map

Anti-Spam Bots!