Skip to content

Commit 3219956

Browse files
authored
Merge pull request #21 from iazaran/Dependency-tracking---Tag-support---Invalidation
Dependency tracking tag support invalidation
2 parents 6a2a457 + 4f984fb commit 3219956

16 files changed

+3472
-29
lines changed

README.md

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ Perfect for **Laravel developers** looking to optimize **cache performance**, re
2020
- 🔄 **Laravel-style helper function** support
2121
- 🎯 **Redis and file cache driver** optimization
2222
- 📊 **Performance monitoring** and cache statistics
23+
- 🔗 **Dependency tracking** - Cascade invalidation with cache hierarchies
24+
- 🎯 **Pattern-based invalidation** - Advanced wildcard and regex pattern matching
25+
- 🏷️ **Tag-based cache management** - Group and flush related cache entries
26+
- 🔄 **Model-based auto-invalidation** - Automatic cache clearing on Eloquent model changes
2327

2428
## 📦 Installation
2529

@@ -86,6 +90,63 @@ public function __construct(\SmartCache\Contracts\SmartCache $cache)
8690
}
8791
```
8892

93+
## 🚀 Advanced Cache Invalidation
94+
95+
SmartCache provides powerful **cache invalidation features** for complex applications:
96+
97+
### 🔗 Dependency Tracking & Cascade Invalidation
98+
99+
Create cache hierarchies where invalidating a parent automatically clears all dependent children:
100+
101+
```php
102+
// Create dependencies
103+
SmartCache::dependsOn('user_posts', 'user_data');
104+
SmartCache::dependsOn('user_stats', 'user_data');
105+
106+
// When user_data is invalidated, user_posts and user_stats are automatically cleared
107+
SmartCache::invalidate('user_data');
108+
```
109+
110+
### 🎯 Pattern-Based Invalidation
111+
112+
Clear multiple cache keys using **wildcards and regex patterns**:
113+
114+
```php
115+
// Wildcard patterns
116+
SmartCache::flushPattern('user_*'); // Clear all user-related keys
117+
SmartCache::flushPattern('api_response_*'); // Clear all API cache
118+
119+
// Regex patterns (advanced)
120+
SmartCache::flushPattern('/user_\d+_profile/'); // Clear user profiles with numeric IDs
121+
```
122+
123+
### 🏷️ Model-Based Auto-Invalidation
124+
125+
Automatically clear cache when **Eloquent models change**:
126+
127+
```php
128+
use SmartCache\Traits\CacheInvalidation;
129+
130+
class User extends Model
131+
{
132+
use CacheInvalidation;
133+
134+
public function getCacheKeysToInvalidate(): array
135+
{
136+
return [
137+
"user_{$this->id}_profile",
138+
"user_{$this->id}_stats",
139+
'users_list_*'
140+
];
141+
}
142+
}
143+
144+
// Cache automatically clears when user is updated/deleted
145+
$user = User::find(123);
146+
$user->name = 'New Name';
147+
$user->save(); // Related cache keys automatically invalidated!
148+
```
149+
89150
## 🔧 Optimization Strategies
90151

91152
SmartCache includes several **cache optimization strategies** that intelligently optimize your data:
@@ -245,8 +306,10 @@ php artisan smart-cache:clear --force
245306

246307
- **Large API response caching** - Optimize storage of external API data
247308
- **Database query result caching** - Cache complex query results efficiently
309+
- **Model-based cache invalidation** - Automatic cache clearing for Eloquent models
310+
- **Complex cache hierarchies** - Dependency tracking and cascade invalidation
311+
- **Pattern-based cache management** - Bulk cache operations with wildcards/regex
248312
- **Session data optimization** - Reduce session storage requirements
249-
- **File-based cache optimization** - Improve file cache performance
250313
- **Redis memory optimization** - Reduce Redis memory usage
251314
- **High-traffic applications** - Improve performance under load
252315

@@ -289,4 +352,4 @@ Laravel SmartCache is open-sourced software licensed under the [MIT license](LIC
289352

290353
Built with ❤️ for developers who care about **Laravel performance optimization** and **efficient caching strategies**.
291354

292-
**Keywords**: Laravel caching, PHP cache optimization, Redis optimization, cache compression, Laravel performance, data chunking, cache management, Laravel package
355+
**Keywords**: Laravel caching, PHP cache optimization, Redis optimization, cache compression, Laravel performance, data chunking, cache management, Laravel package, cache invalidation, model observers, dependency tracking

docs/index.html

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<meta charset="UTF-8">
55
<meta name="viewport" content="width=device-width, initial-scale=1.0">
66
<meta name="description" content="Laravel SmartCache - Intelligent caching optimization package for Laravel applications with compression, chunking, and performance strategies">
7-
<meta name="keywords" content="Laravel, caching, PHP, performance, optimization, Redis, cache management, smart cache, data compression">
7+
<meta name="keywords" content="Laravel, caching, PHP, performance, optimization, Redis, cache management, smart cache, data compression, cache invalidation, model observers, dependency tracking">
88
<meta name="author" content="Ismael Azaran">
99
<title>Laravel SmartCache - Intelligent Caching Optimization</title>
1010
<style>
@@ -106,6 +106,18 @@ <h3>⚙️ Smart Strategy Selection</h3>
106106
<h3>🛡️ Driver Compatibility</h3>
107107
<p>Optional fallback for incompatible cache drivers with seamless integration.</p>
108108
</div>
109+
<div class="feature">
110+
<h3>🔗 Dependency Tracking</h3>
111+
<p>Create cache hierarchies with cascade invalidation for complex data relationships.</p>
112+
</div>
113+
<div class="feature">
114+
<h3>🎯 Pattern Invalidation</h3>
115+
<p>Bulk cache clearing with advanced wildcard and regex pattern matching.</p>
116+
</div>
117+
<div class="feature">
118+
<h3>🔄 Model Auto-Invalidation</h3>
119+
<p>Automatic cache clearing when Eloquent models change using observers and traits.</p>
120+
</div>
109121
</div>
110122

111123
<h2>📦 Installation</h2>
@@ -127,6 +139,26 @@ <h2>🧪 Quick Usage</h2>
127139
smart_cache(['key' => $largeData], 600);
128140
</div>
129141

142+
<h2>🚀 Advanced Cache Invalidation</h2>
143+
<p>SmartCache provides powerful <strong>cache invalidation features</strong> for complex applications:</p>
144+
145+
<div class="code">
146+
// Dependency tracking - cascade invalidation
147+
SmartCache::dependsOn('user_posts', 'user_data');
148+
SmartCache::invalidate('user_data'); // Also clears user_posts
149+
150+
// Pattern-based invalidation
151+
SmartCache::flushPattern('user_*'); // Clear all user cache
152+
SmartCache::flushPattern('/api_\d+/'); // Regex patterns
153+
154+
// Model auto-invalidation
155+
use SmartCache\Traits\CacheInvalidation;
156+
class User extends Model {
157+
use CacheInvalidation;
158+
// Cache cleared automatically on save/delete!
159+
}
160+
</div>
161+
130162
<h2>🎯 Smart Strategy Selection</h2>
131163
<p>SmartCache automatically selects the <strong>best optimization strategy</strong> for your data:</p>
132164
<ul>
@@ -148,8 +180,10 @@ <h2>🔧 Supported Cache Drivers</h2>
148180
<h2>🎯 Use Cases</h2>
149181
<ul>
150182
<li>Large dataset caching (API responses, database queries)</li>
183+
<li>Model-based cache invalidation with Eloquent observers</li>
184+
<li>Complex cache hierarchies with dependency tracking</li>
185+
<li>Pattern-based bulk cache operations (wildcards/regex)</li>
151186
<li>Session data optimization</li>
152-
<li>Complex object serialization</li>
153187
<li>High-traffic application performance</li>
154188
<li>Memory-constrained environments</li>
155189
</ul>
@@ -217,7 +251,7 @@ <h2>📄 License</h2>
217251
"@context": "https://schema.org",
218252
"@type": "SoftwareApplication",
219253
"name": "Laravel SmartCache",
220-
"description": "Intelligent caching optimization package for Laravel applications with compression, chunking, and performance strategies",
254+
"description": "Intelligent caching optimization package for Laravel applications with compression, chunking, cache invalidation, and performance strategies",
221255
"url": "https://github.com/iazaran/smart-cache",
222256
"author": {
223257
"@type": "Person",

src/Contracts/SmartCache.php

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,76 @@ public function clear(): bool;
8787
* @return array
8888
*/
8989
public function getManagedKeys(): array;
90+
91+
/**
92+
* Tag cache entries for organized invalidation.
93+
*
94+
* @param string|array $tags
95+
* @return static
96+
*/
97+
public function tags(string|array $tags): static;
98+
99+
/**
100+
* Flush all cache entries associated with given tags.
101+
*
102+
* @param string|array $tags
103+
* @return bool
104+
*/
105+
public function flushTags(string|array $tags): bool;
106+
107+
/**
108+
* Add cache key dependency relationships.
109+
*
110+
* @param string $key
111+
* @param string|array $dependencies
112+
* @return static
113+
*/
114+
public function dependsOn(string $key, string|array $dependencies): static;
115+
116+
/**
117+
* Invalidate cache key and all dependent keys.
118+
*
119+
* @param string $key
120+
* @return bool
121+
*/
122+
public function invalidate(string $key): bool;
123+
124+
/**
125+
* Flush cache by patterns.
126+
*
127+
* @param array $patterns
128+
* @return int Number of keys invalidated
129+
*/
130+
public function flushPatterns(array $patterns): int;
131+
132+
/**
133+
* Invalidate model-related cache.
134+
*
135+
* @param string $modelClass
136+
* @param mixed $modelId
137+
* @param array $relationships
138+
* @return int Number of keys invalidated
139+
*/
140+
public function invalidateModel(string $modelClass, mixed $modelId, array $relationships = []): int;
141+
142+
/**
143+
* Get cache statistics.
144+
*
145+
* @return array
146+
*/
147+
public function getStatistics(): array;
148+
149+
/**
150+
* Perform health check and cleanup.
151+
*
152+
* @return array
153+
*/
154+
public function healthCheck(): array;
155+
156+
/**
157+
* Get the cache invalidation service.
158+
*
159+
* @return \SmartCache\Services\CacheInvalidationService
160+
*/
161+
public function invalidationService(): \SmartCache\Services\CacheInvalidationService;
90162
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
namespace SmartCache\Observers;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use SmartCache\Traits\CacheInvalidation;
7+
8+
class CacheInvalidationObserver
9+
{
10+
/**
11+
* Handle the model "created" event.
12+
*
13+
* @param Model $model
14+
* @return void
15+
*/
16+
public function created(Model $model): void
17+
{
18+
$this->invalidateCache($model);
19+
}
20+
21+
/**
22+
* Handle the model "updated" event.
23+
*
24+
* @param Model $model
25+
* @return void
26+
*/
27+
public function updated(Model $model): void
28+
{
29+
$this->invalidateCache($model);
30+
}
31+
32+
/**
33+
* Handle the model "deleted" event.
34+
*
35+
* @param Model $model
36+
* @return void
37+
*/
38+
public function deleted(Model $model): void
39+
{
40+
$this->invalidateCache($model);
41+
}
42+
43+
/**
44+
* Handle the model "restored" event.
45+
*
46+
* @param Model $model
47+
* @return void
48+
*/
49+
public function restored(Model $model): void
50+
{
51+
$this->invalidateCache($model);
52+
}
53+
54+
/**
55+
* Perform cache invalidation if the model uses the CacheInvalidation trait.
56+
*
57+
* @param Model $model
58+
* @return void
59+
*/
60+
protected function invalidateCache(Model $model): void
61+
{
62+
if ($this->usesCacheInvalidationTrait($model)) {
63+
$model->performCacheInvalidation();
64+
}
65+
}
66+
67+
/**
68+
* Check if the model uses the CacheInvalidation trait.
69+
*
70+
* @param Model $model
71+
* @return bool
72+
*/
73+
protected function usesCacheInvalidationTrait(Model $model): bool
74+
{
75+
return in_array(CacheInvalidation::class, class_uses_recursive($model));
76+
}
77+
}

0 commit comments

Comments
 (0)