Cache
VelvetCMS provides a unified caching interface with support for multiple drivers and tag-based invalidation.
Namespaces:
VelvetCMS\Contracts\CacheDriver(interface)VelvetCMS\Drivers\Cache\FileCache(file driver)VelvetCMS\Support\Cache\CacheTagManager(tag manager)
CacheDriver Interface #
interface CacheDriver
{
public function get(string $key, mixed $default = null): mixed;
public function set(string $key, mixed $value, int $ttl = 3600): bool;
public function has(string $key): bool;
public function delete(string $key): bool;
public function clear(): bool;
public function remember(string $key, int $ttl, callable $callback): mixed;
}
Methods #
get() #
Retrieve a cached value.
public function get(string $key, mixed $default = null): mixed
| Parameter | Type | Description |
|---|---|---|
$key |
string |
Cache key |
$default |
mixed |
Value if key not found |
Example:
$cache = app('cache');
$name = $cache->get('site.name');
$config = $cache->get('settings', []);
set() #
Store a value in the cache.
public function set(string $key, mixed $value, int $ttl = 3600): bool
| Parameter | Type | Description |
|---|---|---|
$key |
string |
Cache key |
$value |
mixed |
Value to store (serializable) |
$ttl |
int |
Time to live in seconds (0 = forever) |
Example:
// Cache for 5 minutes
$cache->set('user:1', $user, 300);
// Cache for 1 hour (default)
$cache->set('posts:recent', $posts);
// Cache indefinitely
$cache->set('config:app', $config, 0);
has() #
Check if a key exists in cache.
public function has(string $key): bool
Example:
if ($cache->has('user:1')) {
return $cache->get('user:1');
}
delete() #
Remove a key from cache.
public function delete(string $key): bool
Example:
$cache->delete('user:1');
clear() #
Remove all cached items.
public function clear(): bool
Example:
$cache->clear();
remember() #
Get from cache or execute callback and store result.
public function remember(string $key, int $ttl, callable $callback): mixed
| Parameter | Type | Description |
|---|---|---|
$key |
string |
Cache key |
$ttl |
int |
Time to live in seconds |
$callback |
callable |
Function to generate value if not cached |
Example:
// Fetch from cache or database
$posts = $cache->remember('posts:recent', 300, function() {
return $this->postRepository->getRecent(10);
});
// Cache expensive computation
$stats = $cache->remember('analytics:daily', 3600, function() {
return $this->analyticsService->computeDailyStats();
});
CacheTagManager #
Tag-based cache management for group invalidation.
Definition #
class CacheTagManager
{
public function __construct(CacheDriver $cache);
public function remember(string|array $tags, string $key, int $ttl, callable $callback): mixed;
public function set(string|array $tags, string $key, mixed $value, int $ttl = 0): void;
public function delete(string $key): void;
public function flush(string|array $tags): void;
}
remember() #
Cache with tags for later group invalidation.
public function remember(string|array $tags, string $key, int $ttl, callable $callback): mixed
Example:
$tags = app('cache.tags');
// Single tag
$posts = $tags->remember('posts', 'posts:all', 300, fn() => $repo->all());
// Multiple tags
$userPosts = $tags->remember(
['posts', 'users'],
'user:1:posts',
300,
fn() => $repo->getByUser(1)
);
set() #
Store a tagged cache entry.
public function set(string|array $tags, string $key, mixed $value, int $ttl = 0): void
Example:
$tags->set('posts', 'posts:featured', $featuredPosts, 600);
$tags->set(['posts', 'homepage'], 'homepage:posts', $homePosts);
flush() #
Invalidate all cache entries with given tag(s).
public function flush(string|array $tags): void
Example:
// When a post is updated
$tags->flush('posts');
// Clear multiple tag groups
$tags->flush(['posts', 'homepage']);
Configuration #
Configure cache in config/cache.php:
return [
'driver' => env('CACHE_DRIVER', 'file'),
'drivers' => [
'file' => [
'path' => storage_path('cache/data'),
'prefix' => 'velvet',
],
'redis' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'prefix' => 'velvet:',
],
'apcu' => [
'prefix' => 'velvet:',
],
],
];
Usage Examples #
Basic Caching #
$cache = app('cache');
// Simple get/set
$cache->set('key', 'value', 3600);
$value = $cache->get('key');
// Check and get
if ($cache->has('user:session')) {
$session = $cache->get('user:session');
}
// Remember pattern
$data = $cache->remember('expensive:query', 600, function() {
return DB::table('large_table')->get();
});
Page Caching #
class PageService
{
public function __construct(
private CacheDriver $cache,
private CacheTagManager $tags
) {}
public function load(string $slug): Page
{
return $this->cache->remember("page:{$slug}", 300, function() use ($slug) {
return $this->driver->load($slug);
});
}
public function list(array $filters = []): Collection
{
$cacheKey = 'pages:list:' . md5(serialize($filters));
return $this->tags->remember('pages:list', $cacheKey, 300, function() use ($filters) {
return $this->driver->list($filters);
});
}
public function save(Page $page): void
{
$this->driver->save($page);
// Invalidate caches
$this->cache->delete("page:{$page->slug}");
$this->tags->flush('pages:list');
}
}
API Response Caching #
class ApiController
{
public function index(Request $request): Response
{
$page = (int) $request->query('page', 1);
$cacheKey = "api:products:page:{$page}";
$data = app('cache')->remember($cacheKey, 60, function() use ($page) {
return $this->productService->paginate($page, 20);
});
return Response::json($data);
}
}
Cache Invalidation Patterns #
// Event-based invalidation
app('events')->listen('product.saved', function($product) {
$cache = app('cache');
$tags = app('cache.tags');
// Delete specific cache
$cache->delete("product:{$product->id}");
// Flush tag groups
$tags->flush(['products', 'homepage']);
});
// Time-based with short TTL
$cache->remember('volatile:data', 30, fn() => fetchData());
// Manual refresh
public function refresh(string $key): void
{
$this->cache->delete($key);
// Next access will regenerate
}
TTL Reference #
| Duration | Seconds |
|---|---|
| 1 minute | 60 |
| 5 minutes | 300 |
| 15 minutes | 900 |
| 1 hour | 3600 |
| 1 day | 86400 |
| 1 week | 604800 |
| Forever | 0 |