fxcjahid/laravel-eloquent-cache-magic
Composer 安装命令:
composer require fxcjahid/laravel-eloquent-cache-magic
包简介
A lightweight Laravel package for automatic Eloquent query caching with zero-code auto-cache, Redis/Memcached tag support, and automatic cache invalidation
关键字:
README 文档
README
A lightweight Laravel package that adds intelligent caching to your Eloquent queries with zero effort. Features include automatic cache invalidation, Redis/Memcached tag support, and flexible caching options!
📖 Read Complete Documentation - Everything you need to know in one place
✨ Features
- 🚀 Zero Configuration - Works out of the box with sensible defaults
- 🎉 Automatic Query Caching - All queries automatically cached without code changes!
- 🏷️ Cache Tags Support - Full support for Redis and Memcached tagged caching
- 🔄 Automatic Cache Invalidation - Cache automatically clears on model create, update, delete
- 🔧 Flexible API - Multiple ways to configure caching per query
- 🌐 Multi-Driver Support - Works with Redis, Memcached, File, Database drivers
- 🧪 Fully Tested - Comprehensive test coverage with PHPUnit and Pest
- 👤 Auto User/Guest Tags - Automatic user-specific cache isolation
- 🚫 doNotCache() Method - Disable caching for specific queries (DataTables compatible)
- 🎯 Helper Functions - Convenient global functions for cache operations
📋 Requirements
- PHP 8.0 - 8.4
- Laravel 10.0 - 12.0
- Redis or Memcached (optional, for tag support)
📦 Installation
composer require fxcjahid/laravel-eloquent-cache-magic
Optional: Publish Configuration
php artisan vendor:publish --tag=cache-magic-config
Recommended: Setup Redis for Tag Support
composer require predis/predis
CACHE_DRIVER=redis REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
Also update config/database.php
'redis' => [ 'client' => env('REDIS_CLIENT', 'predis'), ]
🚀 Quick Start
🎉 Automatic Query Caching
With auto-cache enabled, ALL your queries are automatically cached without any code changes:
use App\Models\User; use App\Models\Product; // These queries are AUTOMATICALLY cached (no ->cache() needed!) $users = User::all(); // Auto-cached! $product = Product::find(1); // Auto-cached! $count = User::where('active', true)->count(); // Auto-cached! // Bypass auto-cache when you need fresh data $freshUsers = User::withoutCache()->get(); // Skip cache $freshProduct = Product::fresh()->find(1); // Skip cache // Disable auto-cache for specific models class Order extends Model { use CacheableTrait; protected $autoCache = false; // Disable auto-cache for this model }
Manual Caching (Traditional Method)
You can still manually control caching with the ->cache() method:
// Manually cache the query $users = User::where('active', true)->cache()->get(); // Cache for specific duration (in seconds) $users = User::where('active', true)->cache(3600)->get(); // 1 hour // Cache with tags (Redis/Memcached only) $users = User::where('active', true) ->cache() ->tags(['users', 'active']) ->get(); // Clear cache by tags Cache::tags(['users'])->flush(); // Only clears 'users' tagged cache
Model Integration
use Illuminate\Database\Eloquent\Model; use Fxcjahid\LaravelEloquentCacheMagic\Traits\CacheableTrait; class Product extends Model { use CacheableTrait; protected $cacheExpiry = 7200; // 2 hours protected $cacheTags = ['products']; }
🎯 Key Features Explained
🎉 Automatic Query Caching
Enable automatic caching for ALL queries without changing your code:
// In config/cache-magic.php 'auto_cache' => [ 'enabled' => true, // Enable auto-caching 'ttl' => 3600, // Default 1 hour 'aggregate_ttl' => 300, // 5 min for count/sum/avg 'find_ttl' => 7200, // 2 hours for find() ],
Once enabled, all your existing queries are automatically cached:
// These are ALL automatically cached now! User::all(); // Cached for 1 hour Product::find($id); // Cached for 2 hours Order::count(); // Cached for 5 minutes Invoice::where('paid', true)->get(); // Cached for 1 hour // Need fresh data? Bypass cache: User::withoutCache()->all(); // Direct from database Product::fresh()->find($id); // Direct from database
Cache Tags - Smart Invalidation
// Cache with tags for smart invalidation $products = Product::where('category', 'electronics') ->cache() ->tags(['products', 'electronics']) ->get(); // Clear all electronics products Cache::tags(['electronics'])->flush(); // Clear all products Cache::tags(['products'])->flush();
Automatic Cache Invalidation
class Product extends Model { use CacheableTrait; // Cache automatically clears when model is updated/deleted protected $cacheTags = ['products']; // Dynamic tags based on attributes public function dynamicCacheTags(): array { return [ 'category:' . $this->category_id, 'brand:' . $this->brand_id, ]; } }
User/Guest Isolation
Automatically isolate cache by user or guest session:
// In config/cache-magic.php 'auto_user_tags' => [ 'enabled' => true, 'guest_fallback' => 'session', // Options: 'session', 'ip', 'unique' ],
📊 Console Commands
# Clear cache by tags php artisan cache-magic:clear --tags=products # Clear cache by model php artisan cache-magic:clear --model=Product # Clear all cache php artisan cache-magic:clear --all
🔧 Helper Functions
// Cache a callback result $users = cache_remember(['ttl' => 3600, 'tags' => ['users']], function() { return User::all(); }); // Clear cache by tags cache_clear_tags(['products', 'electronics']); // Clear cache by model cache_clear_model(Product::class); // Clear user-specific cache cache_clear_user($userId); // Clear guest cache cache_clear_guest($guestId); // Check if cache supports tags if (cache_supports_tags()) { // Use tag-based caching }
📖 Complete Documentation
Read the complete documentation for comprehensive details on:
- ✅ Installation and configuration
- ✅ All query methods and parameters
- ✅ Cache tags explained with examples
- ✅ Model integration guide
- ✅ Console commands usage
- ✅ Helper functions
- ✅ Advanced features
- ✅ Troubleshooting guide
🧪 Testing
# Run tests vendor/bin/pest # With coverage vendor/bin/pest --coverage
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📝 License
This package is open-sourced software licensed under the MIT license.
👨💻 Author
FXC Jahid
- GitHub: @fxcjahid
- Email: fxcjahid3@gmail.com
🌟 Support
If you find this package helpful, please give it a ⭐ on GitHub!
fxcjahid/laravel-eloquent-cache-magic 适用场景与选型建议
fxcjahid/laravel-eloquent-cache-magic 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「redis」 「performance」 「cache」 「memcached」 「tags」 「optimization」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 fxcjahid/laravel-eloquent-cache-magic 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 fxcjahid/laravel-eloquent-cache-magic 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 fxcjahid/laravel-eloquent-cache-magic 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
g4 application profiler package
repository php library
CSS/Javascript Minificator, Compressor and Concatenator for TYPO3 - highly configurable frontend asset optimization for CSS/JS merging, minification and compression with optional body parsing, async/defer loading, inline output, data-ignore exclusions, SRI integrity validation/calculation, external
WordPress mu-plugin to remove jQuery Migrate from the list of jQuery dependencies and to allow jQuery to enqueue before </body> instead of in the <head>.
Microservice RPC through message queues.
Create link to static resources with cache-breaking segment based on md5 of the file
统计信息
- 总下载量: 25
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 24
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-12