PHP code example of lunzai / laravel-cache-dependency
1. Go to this page and download the library: Download lunzai/laravel-cache-dependency library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
lunzai / laravel-cache-dependency example snippets
use Lunzai\CacheDependency\Facades\CacheDependency;
// Cache with tags
CacheDependency::tags(['users', 'permissions'])
->put('user.1.permissions', $permissions, 3600);
// Retrieve WITHOUT tags
$permissions = CacheDependency::get('user.1.permissions');
// Invalidate — O(1) operation
CacheDependency::invalidateTags('users');
// Cache with tags
CacheDependency::tags(['user.123', 'rbac'])
->put('user.123.permissions', $permissions, 3600);
// Cache with multiple tags
CacheDependency::tags(['user.123', 'role.5', 'rbac'])
->remember('user.123.permissions', 3600, function () {
return $this->calculatePermissions(123);
});
// Retrieve WITHOUT specifying tags
$permissions = CacheDependency::get('user.123.permissions');
// Also works with standard Cache facade
$permissions = Cache::get('user.123.permissions');
// Invalidate all caches with 'rbac' tag (O(1) operation)
CacheDependency::invalidateTags('rbac');
// Invalidate multiple tags at once
CacheDependency::invalidateTags(['user.123', 'role.5']);
// Store indefinitely with tags
CacheDependency::tags('config')->forever('app.settings', $settings);
// Simple DB dependency
CacheDependency::db('SELECT MAX(updated_at) FROM roles')
->remember('all.roles', 3600, fn() => Role::all());
// DB dependency with parameters
CacheDependency::db(
'SELECT MAX(updated_at) FROM role_user WHERE user_id = ?',
[$userId]
)->remember("user.{$userId}.roles", 3600, fn() => $user->roles);
// Using named connection
CacheDependency::db('SELECT COUNT(*) FROM audit_logs')
->connection('audit')
->put('audit.count', $count, 3600);
// Cache is invalidated if:
// - Any tag is invalidated, OR
// - DB query result changes
CacheDependency::tags(['rbac', 'permissions'])
->db('SELECT MAX(updated_at) FROM permissions')
->remember('all.permissions', 3600, fn() => Permission::all());
// Caching user permissions
CacheDependency::tags([
"user.{$userId}.permissions", // Specific cache
"user.{$userId}", // All caches for this user
'user.permissions', // All user permission caches
'rbac', // All RBAC-related caches
])->remember("user.{$userId}.permissions", 3600, fn() => $this->calculatePermissions($userId));
// Invalidation scenarios:
CacheDependency::invalidateTags("user.{$userId}"); // User's roles changed
CacheDependency::invalidateTags('user.permissions'); // Permission logic changed
CacheDependency::invalidateTags('rbac'); // Clear all RBAC caches