Cache Php Class

By August 10, 2010 June 12th, 2015 Development

There are many ready solutions for caching data on php, but I will propose own Cache Php Class. It is quite simple and will help to understand the mechanism of caching.

We will not be caching whole pages, this solution is outdated. In reality, only caching of individual blocks is used. And if more precisely, we will cache only the pure data, no html.

Cacher allows you to cache variables (anything that can be put into a variable) for later use. This speeds up loading time, and reduces load on the data source.

Samples where it can be used

  • caching database queries results;
  • requests from remote servers;
  • getting images or files listings after browsing through the directories, etc.

We use it in our Calypso CMS for caching blocks with the latest posts, menu links tree, portfolio listings, twitter requests etc.

For example, on this page we have 24 mysql queries without caching. With caching – only 9 queries.


Caching hierarchical menu tree from our Calypso CMS:

$cache_key = 'menu-'.$menu['id'];
if(Cache::is_actual($cache_key, 3600)) {
	$tree = Cache::get_cache($cache_key);
else {
	$tree = $this->db->get_tree($menu['id']);
	Cache::put_cache($cache_key, $tree);

Here “3600” is cache lifetime in seconds. If 1 hour from the last time cache generated has not passed, then data is taken from the cache. Otherwise, the “get_tree” method starts, which get entries from the database and builds a hierarchical tree of links.

System requirements

Recommended: PHP 5.2.x
Required: PHP version 5.x.x or higher
PHP versions 4.x are not supported because property visibility and method visibility used (public or private).


Version Downloads Date
1.0 zip (1.01 KB) 2010-August-17

To do

  • Make a single interface, then expand to various storages: filecache, database cache, memcached, etc.
  • Add Cache Manager using 2 design patterns: Strategy and Registry, if we will first use a file cache, and then want to move quickly to memcache.
  • Maybe will add methods to prepare cache by parts and then combine into one piece.