One cache API for PHP over APCu, Redis, Memcached, SQLite, a single binary
file and an in-memory runtime cache. It provides atomic modify(), increment() and decrement(),
invalidation groups, statistics, and settings schemas for building admin forms.
composer require callismart/cacheIt requires PHP 8.1+ and callismart/dto.
Each adapter needs its PHP extension: ext-apcu, ext-redis (phpredis),
ext-memcached or ext-sqlite3. The runtime and binary file adapters need
none.
use Callismart\Cache\Cache;
use Callismart\Cache\CacheGroup;
use Callismart\Cache\Adapters\RedisCacheAdapter;
$redis = new RedisCacheAdapter();
$redis->set_settings( [ 'hostname' => '127.0.0.1', 'port' => 6379, 'prefix' => 'myapp:' ] );
$cache = new Cache( $redis, default_ttl: 3600, prefix: 'myapp' );
$cache->set( 'greeting', 'hello', 60 ); // seconds; 0 = no expiry
$cache->get( 'greeting' ); // 'hello', or false when missing
$cache->increment( 'hits' ); // atomic
$cache->modify( 'list', fn ( $list ) => [ ...$list, 'x' ], 0, [] ); // atomic read-modify-writeEvery adapter returns false for a missing key.
- Default lifetime:
default_ttlmay be a callable. It is read on every call, so a setting changed at runtime applies at once:new Cache( $adapter, fn () : int => (int) $settings->get( 'ttl' ) ). - Shared instance: set it up once with
Cache::instance( $adapter, $default_ttl, $prefix ), then fetch it anywhere withCache::instance().
A cache usually holds two kinds of entry:
- copies of data that can be rebuilt (database rows, API responses);
- state that exists only in the cache (rate-limit counters, one-time tokens).
A group holds the first kind. invalidate() makes every entry in the group
unreachable at once, on every adapter, and leaves everything outside the group
untouched:
$data = $cache->group( CacheGroup::DATA );
$data->set( 'user:1', $user );
$data->invalidate(); // all of the group's entries are gone; counters elsewhere are keptGroup keys are stored as <prefix>_group:<name>:<generation>:<key>. An entry
stored "forever" in a group lives CacheGroup::FOREVER_TTL seconds (one day),
so entries from old generations always expire. Use clear() only for an
administrator's explicit "clear cache": it flushes everything, state included.
CacheAwareTrait gives a class static helpers that work on the data group:
make_cache_key()builds keys that don't depend on parameter order;cache_get(),cache_set()andcache_delete()read and write entries;cache_invalidate()empties the group;default_ttl()returns the cache's default lifetime.
final class Users {
use CacheAwareTrait;
protected static Cache $cache; // set at boot: Users::$cache = Cache::instance()
public static function find( int $id ) : ?array {
$key = static::make_cache_key( __FUNCTION__, [ $id ] );
// cache_get( $key ), then cache_set( $key, $row, static::default_ttl() )
}
}| ID | Class | Persistent | Needs |
|---|---|---|---|
runtime |
Adapters\RuntimeCacheAdapter |
no, the current request only | nothing |
apcu |
Adapters\ApcuCacheAdapter |
yes, on one server | ext-apcu (apc.enable_cli=1 on the command line) |
redis |
Adapters\RedisCacheAdapter |
yes | ext-redis and a Redis server |
memcached |
Adapters\MemcachedCacheAdapter |
yes | ext-memcached and a Memcached server |
sqlitecache |
Adapters\SQLiteCacheAdapter |
yes, on disk | ext-sqlite3 and a writable directory |
binaryfile |
Adapters\BinaryFileCacheAdapter |
yes, on disk | a writable directory on a local disk |
Every adapter implements Adapters\CacheAdapterInterface:
get_id()andget_name();get_settings_schema(): field definitions, withtype,label,defaultanddescription, to build a settings form;set_settings()andtest( $settings ).test()checks a connection without touching the live cache, and throwsExceptions\CacheTestExceptionwith a readable reason;is_supported(),is_active()andis_persistent();get_stats(), which returns aCacheStatswith hits, misses, entries, memory and uptime, plushit_rate().
A persistent cache with no PHP extension: everything is kept in one binary file, with a hash index at the start and records appended after it.
$cache = new Cache( new BinaryFileCacheAdapter( '/var/cache/myapp', 'cache.bin', storage_limit: 256 ) );Speed. Measured on a local ext4 disk with values of about 400 bytes:
| Operation | Binary file | SQLite | APCu |
|---|---|---|---|
| Read | 4 µs | 5 µs | 1 µs |
| Write | 4–6 µs | 160 µs (1.0.0), about 28 µs (1.0.1) | 1 µs |
| Increment | 6 µs | 150 µs | 0.2 µs |
A read takes a shared lock and three small reads. Writes take an exclusive lock: one runs at a time, which allows well over 100,000 a second. A value rewritten with the same size and expiry (counters, tokens) is rewritten in place; anything else is appended. Nothing syncs the disk, so a power loss can lose the last writes.
Damage never returns wrong data. Every record carries a CRC32 and its
full key, and the header carries its own CRC32. A damaged record reads as a
miss and the next write replaces it. A damaged or truncated file is reset,
with an E_USER_NOTICE. A crash at any point leaves only unused bytes.
Space. Replaced and expired records are reclaimed by compaction, which
writes a new file and renames it over the old one (an atomic swap that other
processes follow). It runs when the data has doubled since the last
compaction, when the index is 75% full, or when the file would pass
storage_limit. If live entries alone would fill three quarters of the
limit, the newest are kept, up to half of it. One entry can take at most a
quarter of the limit (16 MB at most).
Limits. Use a local disk: file locks are not reliable on network file
systems, and several servers cannot share the file. Don't delete the file
while it is in use; call clear(). If it is deleted anyway, it is recreated
within a second.
Labels, descriptions and test errors are in English. To translate them, pass the library a translator:
Callismart\Cache\Translation::set_translator( fn ( string $text ) : string => my_translate( $text ) );composer install
vendor/bin/phpunit -d apc.enable_cli=1 # Redis/Memcached tests run when a server answers
composer cs:check- Redis tests: they use
CACHE_REDIS_HOSTandCACHE_REDIS_PORT(default127.0.0.1:6379) and database 15. - Memcached tests: they use
CACHE_MEMCACHED_HOSTandCACHE_MEMCACHED_PORT(default127.0.0.1:11211). - No server: the Redis or Memcached tests are skipped.
MIT