I've discovered (well, technically, never built a caching system before) a nifty way to cache queries. I was working on the API for my CMS (actually, it's more like a general development framework) and this idea just came to me and I thought it'd be nice to share it with you. So, I'll let the code speak for itself
A cacheable API function:
PHP Code:
class API
{
// [declarations, inits, stuff like that...]
public function getPagesList()
{
//---------------------------------------------------------------
// If the current query has not been cached, cache it now
//---------------------------------------------------------------
if( API_Cache::getPagesList() === null )
{
$this->db->select( array( 'what' => '*',
'from' => 'sb_pages',
'orderby' => 'p_order ASC' ) );
if( $this->db->get_rows_number() > 0 )
{
API_Cache::setPagesList( $this->db->get_results() );
}
else
{
API_Cache::setPagesList( array() );
}
}
return API_Cache::getPagesList();
}
}
The caching class:
PHP Code:
class API_Cache
{
private static $pages_list;
protected final function __construct() { }
public static function setPagesList( $value )
{
self::$pages_list = $value;
}
public static function getPagesList()
{
return self::$pages_list;
}
}
So, any ideas or smth? What do you think of this method?
You might ask why did I set the cache class constructor as final and protected. Well, I believe that a caching system like this one, should only act as a library where you store values and then retrieve values from. There's no purpose in embedding logic within it, is there now? So, the class can so easily be extended, but the child classes cannot be instantiated, either.
LE: after a benchmark test, on a set of 30 queries (the same query copy-pasted 30 times), the results were:
- without the cache implementation: 0.0160 seconds (on average)
- with cache: 0.0015 seconds
and on a set of 50 queries:
- without: 0.0250 seconds
- with: 0.0017
Which, I believe is pretty good

But I still need to test it with a more complex query, to see how it would really work when the whole system is done (a SELECT * FROM table_name query was used, so...).