Skip to content

marko/cache-file

File-based cache driver --- persists cached data to disk with automatic expiration and atomic writes. Stores serialized cache entries as individual files, using atomic writes (temp file + rename) to prevent corruption. Expired entries are cleaned up on read. No external services required --- works anywhere PHP can write to disk.

Implements CacheInterface from marko/cache.

Terminal window
composer require marko/cache-file

This automatically installs marko/cache.

Set the cache driver to file in your config:

config/cache.php
return [
'driver' => 'file',
'default_ttl' => 3600,
'path' => 'storage/cache',
];

The path directory is created automatically if it does not exist.

Once configured, inject CacheInterface as usual --- the file driver is used automatically:

use Marko\Cache\Contracts\CacheInterface;
class SettingsService
{
public function __construct(
private CacheInterface $cache,
) {}
public function getAll(): array
{
$key = 'settings.all';
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
$settings = $this->loadFromDatabase();
$this->cache->set($key, $settings, ttl: 7200);
return $settings;
}
}
  • Default choice for most applications
  • No external dependencies (Redis, Memcached, etc.)
  • Data persists across requests and restarts
  • Suitable for single-server deployments

For multi-server deployments or high-throughput caching, use marko/cache-redis.

Implements all methods from CacheInterface. See marko/cache for the full contract.

MethodDescription
get(string $key, mixed $default = null): mixedRetrieve a value, returning $default on miss or expiration
set(string $key, mixed $value, ?int $ttl = null): boolStore a value with optional TTL (falls back to default_ttl)
has(string $key): boolCheck if a non-expired entry exists
delete(string $key): boolRemove a single entry
clear(): boolRemove all cached entries
getItem(string $key): CacheItemInterfaceGet a CacheItem with hit/miss status and expiration metadata
getMultiple(array $keys, mixed $default = null): iterableRetrieve multiple values at once
setMultiple(array $values, ?int $ttl = null): boolStore multiple key-value pairs at once
deleteMultiple(array $keys): boolRemove multiple entries at once
  • Each cache key is hashed with xxh128 and stored as a .cache file in the configured path.
  • Writes use a temp file with LOCK_EX followed by an atomic rename() to prevent corruption.
  • A TTL of 0 or null means the entry never expires.
  • Expired entries are deleted lazily --- on the next get(), has(), or getItem() call for that key.