Part of Jardis — the Domain-Driven Design platform for PHP. You model your domain; Jardis generates the production-ready hexagonal code (DTOs, Command/Query handlers, repositories, persistence). This package is part of the open-source foundation that generated code runs on.
A PSR-16 cache for PHP with multi-layer chaining. Stack Memory, APCu, Redis, and Database backends in a single Cache instance. On a cache miss in a fast layer, the value is automatically backfilled from the next slower layer — so subsequent reads hit the fastest backend available. Writes propagate to all configured layers simultaneously.
- Multi-Layer Chain — Stack any number of backends; reads backfill upper layers automatically
- 5 Backends —
CacheMemory,CacheApcu,CacheRedis,CacheDatabase,CacheNull - PSR-16 — Full
Psr\SimpleCache\CacheInterfaceimplementation on every layer - Namespace Isolation — Each layer instance carries its own namespace prefix
- Immutable After Construction — All layers set via constructor; no mutation at runtime
- Null Object Pattern — Empty
Cache([])degrades gracefully to a no-opCacheNull - TTL Support — Integer seconds or
DateIntervalon everyset()/setMultiple() - Zero Dependencies — No third-party packages required beyond PSR interfaces
composer require jardisadapter/cacheuse JardisAdapter\Cache\Cache;
use JardisAdapter\Cache\Adapter\CacheMemory;
use JardisAdapter\Cache\Adapter\CacheRedis;
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Two-layer cache: L1 = in-process memory, L2 = Redis
$cache = new Cache([
new CacheMemory('myapp'),
new CacheRedis($redis, 'myapp'),
]);
$cache->set('user:42', $userData, ttl: 300);
$user = $cache->get('user:42');CacheRedis and CacheDatabase accept either a ready handle or a provider Closure(): Redis / Closure(): PDO. The provider is not called on construction; it runs on the first cache access (any read, write, or getConnection()), exactly once — the result is reused afterwards. Exceptions thrown by the provider reach the caller unchanged on that first access (they are not turned into graceful-degradation false/$default).
$cache = new Cache([
new CacheRedis(function (): Redis {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
return $redis;
}, 'myapp'),
new CacheDatabase(fn(): PDO => $connectionPool->writer()->pdo(), namespace: 'myapp'),
]);CacheDatabase works on PostgreSQL, MySQL/MariaDB and SQLite. Create the cache table from the schema file for your database in resources/sql/ (pgsql.sql, mysql.sql, sqlite.sql); custom table and column names go into the constructor.
- Supported drivers — the PDO drivers
pgsql,mysql(MySQL and MariaDB) andsqlite. The driver is checked on the firstset(), never on construction. An unknown driver throwsJardisAdapter\Cache\Exception\UnsupportedDatabaseDriverExceptionfromset()(behaviour change: earlier versions reportedfalsefrom the failingREPLACE INTO). - PostgreSQL
UNLOGGED—pgsql.sqlcreates anUNLOGGEDtable: no write-ahead log, so the cache is empty after a server crash and is not replicated to standby servers. - MySQL/MariaDB namespace length — a stored key is the namespace plus a 64-character hash in a
VARCHAR(255)column, so the namespace must not exceed 191 characters. - PostgreSQL and NUL bytes —
cache_valueisTEXT, which cannot hold a NUL byte. A value JSON cannot encode falls back toserialize(); that form may contain a NUL byte (for example a string with"\0"next toINF, or binary data).set()returns false on PostgreSQL when the serialized value contains a NUL byte; a previous value stays. NoBYTEAvariant is offered. - Expired rows —
get()/has()remove an expired entry they hit; other expired rows stay until something callscleanExpired(). The package does not schedule it — give it a caller (cron job, scheduler, worker).
(new CacheDatabase($pdo, namespace: 'orders'))->cleanExpired();CacheDatabase may share the PDO of your application and run inside a transaction you opened. While PDO::inTransaction() is true, every write or delete command — set(), delete(), clear(), cleanExpired() — runs inside a savepoint. If the command fails, it is rolled back to that savepoint and reports false; your transaction stays usable (on PostgreSQL a failed statement would otherwise abort it). A successful command becomes part of your transaction: commit() keeps the entry, rollBack() takes it with it. Reads (get(), has()) run inside a savepoint as well: a failing read (e.g. missing table) returns the default (get()) or false (has()), and your transaction stays usable. Without an open transaction no savepoint is set. With a layer in front of the database layer (e.g. CACHE_LAYERS=memory,db or an apcu layer), rollBack() only removes the database row; the front layer keeps the entry until it expires or the process ends.
$pdo->beginTransaction();
$cache = new CacheDatabase($pdo, namespace: 'orders');
$pdo->prepare('UPDATE orders SET status = :status WHERE id = :id')->execute(['status' => 'paid', 'id' => 42]);
$cache->set('order:42', ['status' => 'paid']); // false on failure, the transaction stays usable
$pdo->rollBack(); // the cache entry is gone as welluse JardisAdapter\Cache\Cache;
use JardisAdapter\Cache\Adapter\CacheMemory;
use JardisAdapter\Cache\Adapter\CacheApcu;
use JardisAdapter\Cache\Adapter\CacheRedis;
use JardisAdapter\Cache\Adapter\CacheDatabase;
// Four-layer cascade: L1 memory → L2 APCu → L3 Redis → L4 database
// A miss at L1 checks L2, then L3, then L4.
// When found, the value is written back into all faster layers automatically.
$cache = new Cache([
new CacheMemory('orders'),
new CacheApcu('orders'),
new CacheRedis($redis, 'orders'),
new CacheDatabase($pdo, namespace: 'orders'),
]);
// Bulk operations — all layers updated in one call
$cache->setMultiple([
'order:101' => $order101,
'order:102' => $order102,
], ttl: 600);
$orders = $cache->getMultiple(['order:101', 'order:102']);
// Invalidate a key across all layers
$cache->delete('order:101');
// Expire stale database entries explicitly
$dbLayer = new CacheDatabase($pdo, namespace: 'orders');
$dbLayer->cleanExpired();Full documentation, guides, and API reference:
docs.jardis.io/en/adapter/cache
This package is licensed under the MIT License.
Jardis · Documentation · Headgent
This package ships with a skill for Claude Code, Cursor, Continue, and Aider. Install it in your consuming project:
composer require --dev jardis/dev-skillsMore details: https://docs.jardis.io/en/skills