Documentation menu

Application services

Cache

Taphra\Cache\Cache stores values between requests: results you compute, query results, and whole page output. It runs on files by default and on APCu, Memcache or Redis when you configure one. Entries expire after a time to live, or when an event they subscribed to is emitted. The last section covers locks, which keep two processes from running the same job at once.

Contents

#

Choosing a driver

#

The driver is caching.method in app/Config/app.yml. The skeleton uses the file driver:

YAML
all:
  caching:
    method: file      # file | apc | memcache | redis
method Stores entries in Needs
file app/tmp/Filecache/, one file per entry a writable app/tmp
apc APCu shared memory of the PHP server ext-apcu
memcache a Memcache server ext-memcache and caching.servers
redis a Redis server, through Predis caching.servers

A Redis cache for production:

YAML
prod:
  caching:
    method: redis
    servers:
      main:
        host: 127.0.0.1
        port: 6379
        database: 1
        password: ""

database defaults to 0. The cache uses one Redis server: list one entry under servers (for several machines, the address of a Redis Cluster, Sentinel or proxy endpoint); a list of more than one is refused with an error, since spreading one cache over independent servers would miss and leave stale entries.

The file and APCu drivers keep entries per machine. With several web servers behind a load balancer, use Redis or Memcache so that every server sees the same entries. When apc or memcache is configured and its extension is missing, Cache::getInstance() logs a warning and returns null.

Storing and reading values

#

Cache::getInstance() returns the shared cache. Times to live are in seconds; 0 means the entry does not expire.

PHP
use Taphra\Cache\Cache;

$cache = Cache::getInstance();

$cache->write('banner.text', 'Free shipping this week', 600);
echo $cache->read('banner.text'), "\n";   // Free shipping this week

$cache->delete('banner.text');
var_dump($cache->read('banner.text'));    // bool(false)

read() returns false for a missing or expired entry, so a stored false cannot be told apart from a miss. Store arrays or strings, or use remember(), which tracks hits itself:

PHP
use Taphra\Cache\Cache;

$stats = Cache::getInstance()->remember('dashboard.stats', 300, function (): array {
    // Runs only when the entry is missing or expired.
    return ['orders' => 128, 'refunds' => 3];
});

remember() takes seconds, a DateInterval, or null for no expiry. The file driver refuses null values (it throws InvalidArgumentException), so a remember() callback must not return null; return false or an empty array instead.

Values are stored with serialize(): arrays, scalars, DataStore rows and collections, DateTime and DateTimeImmutable round-trip. Any other object comes back as __PHP_Incomplete_Class, because the cache reads values back with an allow list of classes, never with unrestricted unserialize(); store such data as arrays. Closures and open resources (database handles, file pointers) cannot be cached.

Caching function output

#

getCachedFunctionOutput($callable, $params, $rules) calls a function once, caches its return value, and serves later calls from the cache. The key is made from the callable and its arguments, so each argument list gets its own entry. A CacheRules object holds the time to live and the events that invalidate the entry.

PHP
use Taphra\Cache\Cache;
use Taphra\Cache\CacheRules;

final class Reports
{
    public static int $runs = 0;

    public static function monthlyTotals(string $month): array
    {
        self::$runs++;
        return ['month' => $month, 'total' => 5400];   // an expensive query in a real app
    }
}

$rules = new CacheRules(['order.paid' => []], 3600);   // [events => params], time to live
$cache = Cache::getInstance();

$a = $cache->getCachedFunctionOutput([Reports::class, 'monthlyTotals'], ['2026-11'], $rules);
$b = $cache->getCachedFunctionOutput([Reports::class, 'monthlyTotals'], ['2026-11'], $rules);
// Reports::$runs === 1: the second call came from the cache

The callable must have a name: a function name, [ClassName::class, 'method'] or [$object, 'method'] (keyed by the object's class). A closure is refused, because the key is built by serialising the callable. Passing null as the rules calls the function without caching.

Caching query results

#

find() and findCount() on a DataStore take a CacheRules object as their last argument and cache the rows they read:

PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

(new SchemaBuilder(DatabaseConnection::load('app_master')))->create('products', function ($t) {
    $t->id();
    $t->string('name', 100);
    $t->integer('stock')->default(0);
});
app/DataStores/ProductDataStore.php
<?php
// app/DataStores/ProductDataStore.php
namespace App\DataStores;

class ProductDataStore extends AppDataStore
{
    public $objectName = 'products';
}
PHP
use App\DataStores\ProductDataStore;
use Taphra\Cache\CacheRules;

$products = new ProductDataStore();
$products->save(['name' => 'Mug', 'stock' => 3]);

$inStock = new CacheRules(['product.changed' => []], 600);
$before  = $products->findCount(['stock >' => 0], $inStock);   // 1, now cached

$products->save(['name' => 'Cap', 'stock' => 5]);
$cached  = $products->findCount(['stock >' => 0], $inStock);   // still 1, from the cache

// find($conditions, $count, $offset, $orderField, $order, $skipHooks, $cacheRules)
$rows = $products->find(['stock >' => 0], 0, 0, 'name', 'ASC', false, $inStock);

The cache key is the query (table, conditions, order, limit) together with the DataStore class and the database it runs on (the connection name, driver, host, port and database or SQLite file, never the credentials): the same query on two databases, or through two DataStore classes, has two entries. Writes do not invalidate it: emit the event the rules name after a change (next section), or keep the time to live short.

Invalidating with events

#

The cache listens to every Event::emit(). Emitting an event deletes the entries whose CacheRules name that event with no parameters:

PHP
use App\DataStores\ProductDataStore;
use Taphra\Cache\CacheRules;
use Taphra\Event;

Event::emit('product.changed');

$fresh = (new ProductDataStore())->findCount(['stock >' => 0], new CacheRules(['product.changed' => []], 600));
// 2: the entry was deleted, so the query ran again

An entry can also subscribe to an event with parameters, for example one product's page: new CacheRules(['product.changed' => ['id' => 7]], 600). Event::emit() passes only the event name to the cache, so these entries are deleted by calling the cache directly with the same parameters:

PHP
use Taphra\Cache\Cache;

Cache::getInstance()->triggerCacheEvent('product.changed', ['id' => 7]);   // true when it deleted something

A good place for the Event::emit() call is the DataStore's afterSave() and afterDelete() hooks, so every write announces itself (see events.md).

Caching page output

#

app/Config/cache.yml caches the output of controller actions without changing the controllers. Each entry is <controller>.<action> in lower case, with a time to live and the events that invalidate it:

app/Config/cache.yml
all:
  catalog:
    index:
      ttl: 600
      events:
        product.changed: ~     # ~ means no parameters
app/Controllers/CatalogController.php
<?php
// app/Controllers/CatalogController.php
namespace App\Controllers;

use App\DataStores\ProductDataStore;

class CatalogController extends AppController
{
    public function index(): string
    {
        $names = array_column(ProductDataStore::all()->toArray(), 'name');
        return '<ul><li>' . implode('</li><li>', array_map('e', $names)) . '</li></ul>';
    }
}

The first request to /catalog runs the action and stores its output; later requests get the stored output until it expires or product.changed is emitted.

Know what the key contains before you cache a page:

  • The key is the controller, the action, the route parameters, the whole query string, the host, the theme and the request headers Accept, Accept-Language, HX-Request, HX-Target and X-Requested-With. The session and the logged-in user are not part of it: every anonymous visitor gets the same output. Cache only pages that are the same for everyone.
  • Only anonymous GET requests use the cache: a request with a session cookie, a remember-me cookie or an Authorization header always runs the action, and a response that starts a session, sets a cookie or has a status other than 200 is not stored.
  • The entry holds the body, the status and the headers that say how to read it: Content-Type, Content-Language, Content-Disposition, Content-Security-Policy (and its report-only form), X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy, the Cross-Origin-*-Policy headers, Vary, Link and htmx's HX-* headers. A hit sends them again, so a cached JSON response stays application/json. Other headers (request ids, cookies) are not stored.

Clearing the cache

#

Cache::getInstance()->clear() deletes the app's entries: the files in app/tmp/Filecache/ for the file driver, and the keys that carry the app's prefix for APCu and Redis. Memcache has no prefixes, so clear() flushes the whole Memcache server.

From the command line:

Shell
php taphra cache:clear

cache:clear also deletes the compiled configuration and translation caches in app/tmp/config_cache/ and app/tmp/lang_cache/; they are rebuilt on the next request. An edited YAML file does not need it: the config caches follow the files' modification time and size (see deployment.md).

A PSR-16 cache for libraries

#

Every driver implements Psr\SimpleCache\CacheInterface. When a library asks for a PSR-16 cache, create a driver directly:

PHP
use Taphra\Cache\FileCacher;

$psr16 = new FileCacher();             // the same app/tmp/Filecache/ folder
$psr16->set('rates.eur', 1.08, 3600);
$rate    = $psr16->get('rates.eur');           // 1.08
$missing = $psr16->get('rates.gbp', 'n/a');    // 'n/a'

PSR-16 rules apply on this interface: keys may not contain {}()/\@:, and an invalid key throws Taphra\Cache\InvalidCacheKeyException.

Locks

#

Taphra\Lock\Lock makes sure only one process runs a piece of work at a time: a nightly import, a report, a scheduled task that may still be running when the next one starts.

PHP
use Taphra\Lock\Lock;

if (Lock::getLock('nightly-import')) {
    try {
        echo "Importing\n";           // the exclusive work
    } finally {
        Lock::releaseLock('nightly-import');
    }
} else {
    echo "An import is already running\n";
}

getLock() does not wait: it returns true when it took the lock and false when another process holds it. Always release the lock in a finally block. A lock is also released when the process that holds it exits.

Two drivers exist. Choose one with lock.method in app.yml, or per call with Lock::getLock('name', LockType::File) (use Taphra\Lock\LockType).

Driver How it locks Scope
file (default) flock() on a file named after the lock in the system temporary directory one machine
database a lock held on the connection you name: GET_LOCK() on MySQL and MariaDB, a session advisory lock on PostgreSQL, a row in a _locks_ table on SQLite every machine using that database
YAML
all:
  lock:
    method: database
    config: app_master    # a connection from databases.yml
    timeout: 5000         # milliseconds to wait for a held lock (default 0: do not wait)
    ttl: 3600             # SQLite only: seconds before a lock expires (default 3600)

On MySQL, MariaDB and PostgreSQL the lock is freed when the connection closes. On SQLite the row expires after ttl seconds, so a crashed holder does not block the name for ever: keep ttl longer than the work the lock protects. Other database types throw an exception. Lock names become file names for the file driver, so use letters, digits, dots and dashes.