Hy guys!
I wanted to speed up my site and my host don't have any memcaching avaidable for objects so I wroted my own Cache class. It's cache to disk not to memory but it's still much faster. Here it is:
Edit: Replaced JSON with serialize because unserialize is faster than json_decode most of the time. JSON_encode is much faster but in a cache we need the fastest reading speed moostly and not the fastest writing speed.
Code:
<?php
/**
* Cache the item/monster etc data to disc.
*/
Class Cache {
private static $instance;
/**
* Return the singleton instance.
*
* @return object the cache singleton
*/
public static function getInstance() {
if (!isset(Cache::$instance)) {
Cache::$instance = new Cache();
}
return Cache::$instance;
}
/**
* Add a new object to the cache. The type and id define the place in the cache,
* the data is the data we want to cache. It use json_encode to save the data.
*
* @param type $type the type of the data eg: item/monster etc...
* @param type $id the id of the data
* @param type $data the data we want to store
*/
public function addObject($type, $id, $data) {
$file = fopen('./cache/' . $type . '/' . $type . '_' . $id . '.cch', 'w');
fwrite($file, serialize($data));
fclose($file);
}
/**
* Return and object from the cache. The type and id define the place in the cache
* we are reading from. It use json_decode to get the array from file.
*
* @param type $type the type of the data eg: item/monster etc...
* @param type $id the id of the data
* @return array the data array
*/
public function getObject($type, $id) {
$fh = fopen('./cache/' . $type . '/' . $type . '_' . $id . '.cch', 'r');
$data = fread($fh, filesize('./cache/' . $type . '/' . $type . '_' . $id . '.cch'));
return unserialize($data);
}
/**
* Check that data is stored with the given type and id.
*
* @param type $type the type position
* @param type $id the id position
* @return boolean true if found false if not
*/
public function isCached($type, $id) {
return file_exists('./cache/' . $type . '/' . $type . '_' . $id . '.cch');
}
/**
* Cloning is blocked because of the singleton pattern.
*/
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
/**
* Wakeup is blocked because of the singleton pattern.
*/
public function __wakeup() {
trigger_error('Unserializing is not allowed.', E_USER_ERROR);
}
/**
* Construct is private because of the singleton pattern.
*/
private function __construct() {
}
}
?>
It runs 2.5x faster than using plain SQL.