Your new favourite file-based cache library

2.3.0 2013-04-12 17:47 UTC


The goal of this project is not to replace some advanced libraries like Memcached, APC, Redis... etc, but offer a good solution for shared hostings or small/medium projects.

CacheGadget is easy and fast, use it with no pain!

Api docs (Generated by Apigen)

Installation using Composer

    "require": {
        "cachegadget/cachegadget": "2.3.0"



require 'vendor/autoload.php';

$cache = new CacheGadget\CacheGadget();

Manual Installation

CacheGadget is a one-file library, clone the repo, download last tag, or get the php library and include it in your project.


Basic example.


$cache = new CacheGadget\CacheGadget('./cache');

if (!$content = $cache->get('my_key')) {
    $content = 'This text will be cached';
    // save cache, default expiration time 60 secs
    $cache->set('my_key', $content);

    // set other expiration time, 300 secs
    // $cache->set('my_key', $content, 300);

echo $content;

More at demo file.

How it works?

All keys are saved in categories. There are a main cache directory with subdirectories that are categories. Each key in a single file. If you don't set a category CacheGadget uses the default category called "default" so all keys (files) are saved inside this directory ./cache/default/KEY_NAME_AS_MD5 or ./cache/CATEGORY_NAME/KEY_NAME_AS_MD5

CacheGadget save every cached file in an array converted to JSON. For example, we want to cache a variable:

$my_var = 'I want to cache this text';
$cache->set('my_var', $my_var);

This internally generate an array...

$cache = array(
    'expiration' => 280, // seconds to expire
    'time' => time(), // actual time, used to compare with expiration when retrieve
    'data' => 'I want to cache this text',

...and save using json_encode. When retrieve the key with $cache->get('my_var') CacheGadget compare his expiration time, if not expired return the index data.

Public methos

  • get(): Retrieve a key
  • set(): Create new key or replace if exists
  • add(): Create new key only if not exists (prevent overwrite)
  • remove(): Remove only one key
  • flush(): Remove all keys in one category
  • clear(): Remove all keys in all categories.
  • touch(): Change expiration time of a key
  • exists(): Return true/false if key exists
  • increment(): Increment the value of a numeric stored key

See params and more methods at Api docs.


Mainteined by Jordi Enguídanos. MIT Lisence