Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 65 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ Perfect for **Laravel developers** looking to optimize **cache performance**, re
- 🔄 **Laravel-style helper function** support
- 🎯 **Redis and file cache driver** optimization
- 📊 **Performance monitoring** and cache statistics
- 🔗 **Dependency tracking** - Cascade invalidation with cache hierarchies
- 🎯 **Pattern-based invalidation** - Advanced wildcard and regex pattern matching
- 🏷️ **Tag-based cache management** - Group and flush related cache entries
- 🔄 **Model-based auto-invalidation** - Automatic cache clearing on Eloquent model changes

## 📦 Installation

Expand Down Expand Up @@ -86,6 +90,63 @@ public function __construct(\SmartCache\Contracts\SmartCache $cache)
}
```

## 🚀 Advanced Cache Invalidation

SmartCache provides powerful **cache invalidation features** for complex applications:

### 🔗 Dependency Tracking & Cascade Invalidation

Create cache hierarchies where invalidating a parent automatically clears all dependent children:

```php
// Create dependencies
SmartCache::dependsOn('user_posts', 'user_data');
SmartCache::dependsOn('user_stats', 'user_data');

// When user_data is invalidated, user_posts and user_stats are automatically cleared
SmartCache::invalidate('user_data');
```

### 🎯 Pattern-Based Invalidation

Clear multiple cache keys using **wildcards and regex patterns**:

```php
// Wildcard patterns
SmartCache::flushPattern('user_*'); // Clear all user-related keys
SmartCache::flushPattern('api_response_*'); // Clear all API cache

// Regex patterns (advanced)
SmartCache::flushPattern('/user_\d+_profile/'); // Clear user profiles with numeric IDs
```

### 🏷️ Model-Based Auto-Invalidation

Automatically clear cache when **Eloquent models change**:

```php
use SmartCache\Traits\CacheInvalidation;

class User extends Model
{
use CacheInvalidation;

public function getCacheKeysToInvalidate(): array
{
return [
"user_{$this->id}_profile",
"user_{$this->id}_stats",
'users_list_*'
];
}
}

// Cache automatically clears when user is updated/deleted
$user = User::find(123);
$user->name = 'New Name';
$user->save(); // Related cache keys automatically invalidated!
```

## 🔧 Optimization Strategies

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

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

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

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

**Keywords**: Laravel caching, PHP cache optimization, Redis optimization, cache compression, Laravel performance, data chunking, cache management, Laravel package
**Keywords**: Laravel caching, PHP cache optimization, Redis optimization, cache compression, Laravel performance, data chunking, cache management, Laravel package, cache invalidation, model observers, dependency tracking
40 changes: 37 additions & 3 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Laravel SmartCache - Intelligent caching optimization package for Laravel applications with compression, chunking, and performance strategies">
<meta name="keywords" content="Laravel, caching, PHP, performance, optimization, Redis, cache management, smart cache, data compression">
<meta name="keywords" content="Laravel, caching, PHP, performance, optimization, Redis, cache management, smart cache, data compression, cache invalidation, model observers, dependency tracking">
<meta name="author" content="Ismael Azaran">
<title>Laravel SmartCache - Intelligent Caching Optimization</title>
<style>
Expand Down Expand Up @@ -106,6 +106,18 @@ <h3>⚙️ Smart Strategy Selection</h3>
<h3>🛡️ Driver Compatibility</h3>
<p>Optional fallback for incompatible cache drivers with seamless integration.</p>
</div>
<div class="feature">
<h3>🔗 Dependency Tracking</h3>
<p>Create cache hierarchies with cascade invalidation for complex data relationships.</p>
</div>
<div class="feature">
<h3>🎯 Pattern Invalidation</h3>
<p>Bulk cache clearing with advanced wildcard and regex pattern matching.</p>
</div>
<div class="feature">
<h3>🔄 Model Auto-Invalidation</h3>
<p>Automatic cache clearing when Eloquent models change using observers and traits.</p>
</div>
</div>

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

<h2>🚀 Advanced Cache Invalidation</h2>
<p>SmartCache provides powerful <strong>cache invalidation features</strong> for complex applications:</p>

<div class="code">
// Dependency tracking - cascade invalidation
SmartCache::dependsOn('user_posts', 'user_data');
SmartCache::invalidate('user_data'); // Also clears user_posts

// Pattern-based invalidation
SmartCache::flushPattern('user_*'); // Clear all user cache
SmartCache::flushPattern('/api_\d+/'); // Regex patterns

// Model auto-invalidation
use SmartCache\Traits\CacheInvalidation;
class User extends Model {
use CacheInvalidation;
// Cache cleared automatically on save/delete!
}
</div>

<h2>🎯 Smart Strategy Selection</h2>
<p>SmartCache automatically selects the <strong>best optimization strategy</strong> for your data:</p>
<ul>
Expand All @@ -148,8 +180,10 @@ <h2>🔧 Supported Cache Drivers</h2>
<h2>🎯 Use Cases</h2>
<ul>
<li>Large dataset caching (API responses, database queries)</li>
<li>Model-based cache invalidation with Eloquent observers</li>
<li>Complex cache hierarchies with dependency tracking</li>
<li>Pattern-based bulk cache operations (wildcards/regex)</li>
<li>Session data optimization</li>
<li>Complex object serialization</li>
<li>High-traffic application performance</li>
<li>Memory-constrained environments</li>
</ul>
Expand Down Expand Up @@ -217,7 +251,7 @@ <h2>📄 License</h2>
"@context": "https://schema.org",
"@type": "SoftwareApplication",
"name": "Laravel SmartCache",
"description": "Intelligent caching optimization package for Laravel applications with compression, chunking, and performance strategies",
"description": "Intelligent caching optimization package for Laravel applications with compression, chunking, cache invalidation, and performance strategies",
"url": "https://github.com/iazaran/smart-cache",
"author": {
"@type": "Person",
Expand Down
72 changes: 72 additions & 0 deletions src/Contracts/SmartCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,76 @@ public function clear(): bool;
* @return array
*/
public function getManagedKeys(): array;

/**
* Tag cache entries for organized invalidation.
*
* @param string|array $tags
* @return static
*/
public function tags(string|array $tags): static;

/**
* Flush all cache entries associated with given tags.
*
* @param string|array $tags
* @return bool
*/
public function flushTags(string|array $tags): bool;

/**
* Add cache key dependency relationships.
*
* @param string $key
* @param string|array $dependencies
* @return static
*/
public function dependsOn(string $key, string|array $dependencies): static;

/**
* Invalidate cache key and all dependent keys.
*
* @param string $key
* @return bool
*/
public function invalidate(string $key): bool;

/**
* Flush cache by patterns.
*
* @param array $patterns
* @return int Number of keys invalidated
*/
public function flushPatterns(array $patterns): int;

/**
* Invalidate model-related cache.
*
* @param string $modelClass
* @param mixed $modelId
* @param array $relationships
* @return int Number of keys invalidated
*/
public function invalidateModel(string $modelClass, mixed $modelId, array $relationships = []): int;

/**
* Get cache statistics.
*
* @return array
*/
public function getStatistics(): array;

/**
* Perform health check and cleanup.
*
* @return array
*/
public function healthCheck(): array;

/**
* Get the cache invalidation service.
*
* @return \SmartCache\Services\CacheInvalidationService
*/
public function invalidationService(): \SmartCache\Services\CacheInvalidationService;
}
77 changes: 77 additions & 0 deletions src/Observers/CacheInvalidationObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace SmartCache\Observers;

use Illuminate\Database\Eloquent\Model;
use SmartCache\Traits\CacheInvalidation;

class CacheInvalidationObserver
{
/**
* Handle the model "created" event.
*
* @param Model $model
* @return void
*/
public function created(Model $model): void
{
$this->invalidateCache($model);
}

/**
* Handle the model "updated" event.
*
* @param Model $model
* @return void
*/
public function updated(Model $model): void
{
$this->invalidateCache($model);
}

/**
* Handle the model "deleted" event.
*
* @param Model $model
* @return void
*/
public function deleted(Model $model): void
{
$this->invalidateCache($model);
}

/**
* Handle the model "restored" event.
*
* @param Model $model
* @return void
*/
public function restored(Model $model): void
{
$this->invalidateCache($model);
}

/**
* Perform cache invalidation if the model uses the CacheInvalidation trait.
*
* @param Model $model
* @return void
*/
protected function invalidateCache(Model $model): void
{
if ($this->usesCacheInvalidationTrait($model)) {
$model->performCacheInvalidation();
}
}

/**
* Check if the model uses the CacheInvalidation trait.
*
* @param Model $model
* @return bool
*/
protected function usesCacheInvalidationTrait(Model $model): bool
{
return in_array(CacheInvalidation::class, class_uses_recursive($model));
}
}
Loading