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);

'db' => [
    'fail_open' => false, // Default: fail closed
],

// 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

// Product cache
CacheDependency::tags([
    "product.{$productId}",
    "category.{$categoryId}.products",
    "vendor.{$vendorId}.products",
    'products',
])->remember("product.{$productId}", 3600, fn() => Product::find($productId));

// Invalidation:
CacheDependency::invalidateTags("product.{$productId}");           // Product updated
CacheDependency::invalidateTags("category.{$categoryId}.products"); // Category products changed

// Tenant-scoped cache
CacheDependency::tags([
    "tenant.{$tenantId}",
    "tenant.{$tenantId}.settings",
])->remember("tenant.{$tenantId}.config", 3600, fn() => $tenant->settings);

// Invalidation:
CacheDependency::invalidateTags("tenant.{$tenantId}");  // Clear all tenant caches

return [
    // Cache store to use (null = default)
    'store' => env('CACHE_DEPENDENCY_STORE'),

    // Prefix for internal cache keys (tag versions)
    'prefix' => env('CACHE_DEPENDENCY_PREFIX', 'cdep'),

    // Tag version TTL (should be longer than longest cache TTL)
    'tag_version_ttl' => env('CACHE_DEPENDENCY_TAG_TTL', 86400 * 30), // 30 days

    'db' => [
        // Default database connection (null = default)
        'connection' => env('CACHE_DEPENDENCY_DB_CONNECTION'),

        // Query timeout in seconds
        'timeout' => env('CACHE_DEPENDENCY_DB_TIMEOUT', 5),

        // Behavior when DB query fails:
        // - false: Return null (cache miss) - fail closed
        // - true: Return cached value (fail open)
        'fail_open' => env('CACHE_DEPENDENCY_FAIL_OPEN', false),
    ],
];

// Create pending dependency with tags
CacheDependency::tags(array|string $tags): PendingDependency

// Create pending dependency with DB query
CacheDependency::db(string $sql, array $params = []): PendingDependency

// Retrieve from cache
CacheDependency::get(string $key, mixed $default = null): mixed

// Store in cache (without dependencies)
CacheDependency::put(string $key, mixed $value, ?int $ttl = null): bool

// Remember pattern
CacheDependency::remember(string $key, ?int $ttl, Closure $callback): mixed

// Invalidate tags (O(1))
CacheDependency::invalidateTags(array|string $tags): void

// Get tag version
CacheDependency::getTagVersion(string $tag): int

// Check existence (checks staleness)
CacheDependency::has(string $key): bool

// Remove from cache
CacheDependency::forget(string $key): bool

// Retrieve and delete
CacheDependency::pull(string $key, mixed $default = null): mixed

// Get multiple
CacheDependency::many(array $keys): array

// Clear all
CacheDependency::flush(): bool

// Use different store
CacheDependency::store(?string $name = null): CacheDependencyManager

// Add tags (chainable)
->tags(array|string $tags): self

// Set DB dependency (chainable)
->db(string $sql, array $params = []): self

// Set DB connection (chainable)
->connection(string $connection): self

// Store with dependencies
->put(string $key, mixed $value, ?int $ttl = null): bool

// Remember with dependencies
->remember(string $key, ?int $ttl, Closure $callback): mixed

// Store forever with dependencies
->forever(string $key, mixed $value): bool

// Store multiple with dependencies
->putMany(array $values, ?int $ttl = null): bool
bash
php artisan vendor:publish --tag="cache-dependency-config"
bash
php artisan vendor:publish --tag="cache-dependency-config"