iazaran/smart-cache

Smart Cache is a caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.


README

Latest Version License PHP Version

Laravel SmartCache is a powerful caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.

Perfect for Laravel developers looking to optimize cache performance, reduce memory usage, and improve application speed with intelligent data compression and cache management.

๐Ÿš€ Features

  • ๐Ÿ” Auto-detects large cache payloads - Automatically identifies when optimization is needed
  • ๐Ÿ“ฆ Compresses data before caching - Reduces storage requirements with gzip compression
  • ๐Ÿงฉ Chunks large arrays or objects into manageable parts for better performance
  • ๐Ÿง  Intelligent serialization - Advanced data serialization techniques
  • โ™ป๏ธ Seamless retrieval and reconstruction - Transparent data recovery
  • โš™๏ธ Extensible strategy pattern for custom optimizations
  • ๐Ÿ›ก๏ธ Optional fallback for incompatible drivers
  • ๐Ÿ”„ Laravel-style helper function support
  • ๐ŸŽฏ Redis and file cache driver optimization
  • ๐Ÿ“Š Performance monitoring and cache statistics

๐Ÿ“ฆ Installation

Install the package via Composer:

composer require iazaran/smart-cache

Requirements: Laravel 8+ is supported. Tested with Redis and file cache drivers.

โš™๏ธ Configuration

After installation, publish the config file:

php artisan vendor:publish --tag=smart-cache-config

The config file allows you to define thresholds, compression strategies, chunk sizes, and enabled features.

๐Ÿงช Usage

Basic Usage with SmartCache Facade

Use SmartCache just like Laravel's Cache facade:

use SmartCache\Facades\SmartCache;

// Store large data with automatic optimization
SmartCache::put('user_data', $largeUserArray, now()->addMinutes(10));

// Retrieve data seamlessly
$userData = SmartCache::get('user_data');

Helper Function Usage

Or use the global helper function, similar to Laravel's cache() helper:

// Get a value
$value = smart_cache('cache_key');

// Get with default value
$value = smart_cache('cache_key', 'default_value');

// Store a value with automatic optimization
smart_cache(['large_dataset' => $bigArray], now()->addMinutes(10));

// Access the SmartCache instance
$cache = smart_cache();

Dependency Injection

Or inject it into your services:

public function __construct(\SmartCache\Contracts\SmartCache $cache)
{
    $this->cache = $cache;
}

๐Ÿ”ง Optimization Strategies

SmartCache includes several cache optimization strategies that intelligently optimize your data:

๐ŸŽฏ Strategy Selection & Priority

SmartCache automatically selects the best optimization strategy for your data:

  1. Chunking Strategy (Priority 1)

    • Applied to large arrays/collections with many items
    • Splits data into manageable chunks for better performance
    • Best for: Large datasets, API response arrays, database result sets
  2. Compression Strategy (Priority 2)

    • Applied to large strings, arrays, and objects
    • Uses gzip compression to reduce cache size
    • Best for: Text data, serialized objects, repetitive content
  3. No Optimization (Default)

    • Small data stays unchanged for optimal performance
    • No overhead for data that doesn't benefit from optimization

๐Ÿง  Intelligent Strategy Application

Each strategy evaluates the original data independently to determine if it should apply:

  • Data Type Matching: Chunking only applies to arrays/collections, compression works on all types
  • Size Thresholds: Each strategy has configurable size thresholds
  • Driver Compatibility: Strategies respect cache driver limitations
  • Performance Optimization: Only one strategy is applied per value (no chaining overhead)

๐Ÿ› ๏ธ Built-in Strategies

  • Compression: Uses gzip compression with configurable levels (1-9)
  • Chunking: Splits large arrays into configurable chunk sizes
  • Encoding: Safe serialization for different cache drivers
  • Driver-Aware: Automatically adapts to your cache driver capabilities

โš™๏ธ Extensible Architecture

Create custom strategies by implementing SmartCache\Contracts\OptimizationStrategy:

class CustomStrategy implements OptimizationStrategy
{
    public function shouldApply(mixed $value, array $context = []): bool
    {
        // Your optimization criteria
    }
    
    public function optimize(mixed $value, array $context = []): mixed
    {
        // Your optimization logic
    }
    
    public function restore(mixed $value, array $context = []): mixed
    {
        // Your restoration logic
    }
}

๐Ÿ“‚ Example: Large Dataset Caching

// Example: Caching large API response data
$apiData = range(1, 10000); // Large dataset
$complexObject = [
    'users' => $userCollection,
    'metadata' => $metadataArray,
    'statistics' => $statsData
];

// SmartCache automatically selects the best optimization
SmartCache::put('api_response', $complexObject, 600);

// Behind the scenes:
// - Evaluates all strategies against original data
// - Selects best strategy (chunking for large arrays, compression for others)
// - Applies single optimal transformation
// - Stores optimization metadata for retrieval
// - Ensures fast reconstruction

// Retrieve optimized data
$retrievedData = SmartCache::get('api_response');

// Or with helper function
smart_cache(['api_response' => $complexObject], 600);

๐ŸŽฏ Strategy Selection Examples

// Large array with many items โ†’ Chunking applied
$manyUsers = User::all(); // 5000+ user records
SmartCache::put('all_users', $manyUsers); // โ†’ Chunked storage

// Large string content โ†’ Compression applied  
$largeText = file_get_contents('large_file.txt'); // 100KB text
SmartCache::put('file_content', $largeText); // โ†’ Compressed storage

// Medium array with large items โ†’ Compression applied
$reports = [ /* 50 items with large content each */ ];
SmartCache::put('reports', $reports); // โ†’ Compressed storage

// Small data โ†’ No optimization (fastest)
$config = ['setting' => 'value'];
SmartCache::put('config', $config); // โ†’ Stored as-is

๐Ÿงฐ Artisan Commands

SmartCache provides powerful Artisan commands for cache management and monitoring:

๐Ÿ“Š Status Command

View SmartCache usage and configuration details:

# Basic status - shows SmartCache managed keys and configuration
php artisan smart-cache:status

# Enhanced status with Laravel cache analysis
php artisan smart-cache:status --force

What --force shows:

  • โœ… Orphaned key detection - Find SmartCache-related keys that aren't properly tracked
  • ๐Ÿ” Missing key validation - Identify managed keys that no longer exist in cache
  • ๐Ÿงน Cache health insights - Get suggestions for cleanup and optimization

๐Ÿ—‘๏ธ Clear Command

Flexible cache clearing with precise control:

# Clear only SmartCache managed items (safe)
php artisan smart-cache:clear

# Clear a specific managed key
php artisan smart-cache:clear my-optimized-key

# Clear any key in Laravel cache, even if not managed by SmartCache
php artisan smart-cache:clear some-laravel-key --force

# Clear all managed keys + cleanup orphaned SmartCache keys
php artisan smart-cache:clear --force

When to use --force:

  • ๐Ÿ”ง Cleanup orphaned keys - Remove leftover SmartCache chunks or metadata
  • ๐ŸŽฏ Clear non-managed keys - Remove regular Laravel cache keys when needed
  • ๐Ÿงน Deep cleanup - Comprehensive cache maintenance and optimization

๐ŸŽฏ Use Cases

  • Large API response caching - Optimize storage of external API data
  • Database query result caching - Cache complex query results efficiently
  • 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

๐Ÿ“Š Performance Benefits

  • Up to 70% reduction in cache storage size
  • Faster cache retrieval for large datasets
  • Reduced memory usage in Redis and other drivers
  • Improved application response times
  • Better resource utilization

๐Ÿ”ง Supported Cache Drivers

  • โœ… Redis - Full feature support with compression and chunking
  • โœ… File Cache - Optimized file-based caching
  • โœ… Database - Database cache driver optimization
  • โœ… Array - In-memory cache optimization
  • โš ๏ธ Memcached - Basic support (limited chunking)

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details on:

  • Reporting bugs
  • Suggesting features
  • Submitting pull requests
  • Code style guidelines

๐Ÿ“„ License

Laravel SmartCache is open-sourced software licensed under the MIT license.

๐Ÿ”— Links

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