Cache Overview
Cache drivers, configuration, and usage patterns.
VelvetCMS includes a simple but flexible caching system. Cache operations are designed to fail gracefully-if something goes wrong, your app continues with uncached data instead of crashing.
Available Drivers #
| Driver | Use Case |
|---|---|
| File | Default, works everywhere, no setup required |
| Redis | High-performance, shared cache across servers |
| APCu | Fast in-memory cache, single-server only |
Basic Usage #
Get the cache via the container:
$cache = app('cache');
// Store a value for 5 minutes
$cache->set('user:123', $userData, 300);
// Retrieve it
$user = $cache->get('user:123');
// With default fallback
$user = $cache->get('user:123', null);
Remember Pattern #
The remember() method handles the common "fetch from cache or compute" pattern:
$posts = $cache->remember('recent-posts', 600, function () {
return $this->db->table('posts')
->orderBy('created_at', 'desc')
->limit(10)
->get();
});
If the key exists and hasn't expired, it returns the cached value. Otherwise, it runs the callback, caches the result, and returns it.
Driver Configuration #
Set your driver in config/cache.php or user/config/cache.php:
return [
'default' => 'file', // or 'redis', 'apcu'
'prefix' => 'velvet',
'drivers' => [
'file' => [
'path' => storage_path('cache'),
],
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'password' => null,
'database' => 0,
],
'apcu' => [],
],
];
File Driver #
The file driver stores serialized data in storage/cache. It uses two-character directory sharding to avoid filesystem limits on large caches. Cache entries are signed with an HMAC to detect tampering.
Redis Driver #
Redis requires the PHP redis extension. It supports persistent connections and automatic key prefixing. All operations are wrapped in try/catch to handle connection failures gracefully.
'redis' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'password' => env('REDIS_PASSWORD'),
'database' => 0,
],
APCu Driver #
APCu caches directly in PHP's shared memory. It's the fastest option but only works within a single server-cached data isn't shared between servers.
Cache Operations #
$cache = app('cache');
// Check if key exists
if ($cache->has('settings')) {
// ...
}
// Delete a key
$cache->delete('user:123');
// Clear everything
$cache->clear();
Error Handling #
Cache drivers are designed to fail open. If Redis is down or the filesystem is full:
get()returns the default valueset()returnsfalse- Your application continues working
This design means you never need to wrap cache calls in try/catch-failures are silent by default.
Multi-Tenancy #
When tenancy is enabled, the cache prefix is automatically extended with the tenant ID. File cache paths resolve under the tenant's storage directory. No code changes needed.
What's Next #
- Cache Tags - group-based invalidation
- Cache Configuration - all config options