Caching & Performance
Caching and performance packages provide various optimization strategies for different layers of the application.
laravel-file-storage-cache
Section titled “laravel-file-storage-cache”Filesystem-based cache store using cloud storage (S3, Azure Blob, etc.).
Key Features
Section titled “Key Features”- Cloud storage as cache backend
- Hash-based directory sharding
- Metadata-based TTL tracking
- Works with any Flysystem adapter
Service Provider
Section titled “Service Provider”FileStorageCacheServiceProvider extends Laravel’s CacheManager.
Configuration
Section titled “Configuration”'stores' => [ 'file_storage' => [ 'driver' => 'file_storage', 'disk' => 's3', // Flysystem disk name 'path_prefix' => 'cache', // Optional prefix ],],// Standard cache operationsCache::store('file_storage')->put('key', $value, 3600);$value = Cache::store('file_storage')->get('key');Cache::store('file_storage')->forget('key');Cache::store('file_storage')->flush();
// Multi-key operationsCache::store('file_storage')->getMany(['key1', 'key2']);Cache::store('file_storage')->putMany(['k1' => $v1, 'k2' => $v2], 3600);Implementation Details
Section titled “Implementation Details”- Path Sharding: 2-level SHA1 sharding (
{prefix}/ab/abcd...xyz/) - File Extensions:
.cache_dataand.cache_metadata - Unsupported:
increment(),decrement(),forever()
laravel-command-cache
Section titled “laravel-command-cache”Console commands for managing multiple cache layers.
Key Features
Section titled “Key Features”- Redis cache management
- APCu cache management
- Opcache management
- Tag-based and pattern-based flushing
- Cache statistics and slowlog analysis
Commands
Section titled “Commands”Flush Command
Section titled “Flush Command”# Redis - flush allphp artisan cache:flush redis --all
# Redis - by tagphp artisan cache:flush redis --tag=users --tag=posts
# Redis - by glob patternphp artisan cache:flush redis --glob='cache:user:*'
# Redis - by keyphp artisan cache:flush redis --key=my_key
# APCu - by regexphp artisan cache:flush apcu --regex='cache:.*:profile'
# Opcachephp artisan cache:flush opcache
# Custom PHP-FPM socketphp artisan cache:flush apcu --socket=/var/run/php/php8.4-fpm.sockStats Command
Section titled “Stats Command”# Redis statsphp artisan cache:stats redis
# Redis slowlogphp artisan cache:stats redis --slowlog=10
# APCu statsphp artisan cache:stats apcu
# Opcache statsphp artisan cache:stats opcacheFilter Support
Section titled “Filter Support”| Filter | Redis | APCu | Opcache |
|---|---|---|---|
--all | ✓ | ✓ | ✓ |
--tag | ✓ | ✗ | ✗ |
--glob | ✓ | ✗ | ✗ |
--key | ✓ | ✓ | ✗ |
--regex | ✗ | ✓ | ✗ |
PHP-FPM Socket Communication
Section titled “PHP-FPM Socket Communication”APCu and Opcache require PHP-FPM socket access since they’re not accessible from CLI:
// Uses hollodotme/fast-cgi-clienttrait ConnectsPhpFpmSocket { protected function executeInFpm(string $code): string;}laravel-http-cache-control
Section titled “laravel-http-cache-control”HTTP response caching headers and ETag support.
Key Features
Section titled “Key Features”- ETag generation and validation
- Cache-Control header management
- Vary header for cache key variation
- 304 Not Modified responses
Service Provider
Section titled “Service Provider”LaravelHttpCacheControlServiceProvider publishes configuration.
Middleware
Section titled “Middleware”// Register globally or per-routeprotected $middleware = [ \RightCapital\LaravelHttpCacheControl\SetCacheHeaders::class,];
// Or per routeRoute::get('/api/data', fn() => [...]) ->middleware('setcacheheaders');Configuration
Section titled “Configuration”return [ 'vary' => [ 'Accept', 'Authorization', 'Cookie', ],
'cache-control' => [ 'public', // Cacheable by CDN 'max-age=3600', // Browser cache 1 hour 's-maxage=86400', // CDN cache 24 hours 'must-revalidate', ],];Response Headers
Section titled “Response Headers”Cache-Control: public, max-age=3600, s-maxage=86400, must-revalidateETag: W/"e81fe3a0d3d3aa0a3f6d2b5c3d2e1a0b"Vary: Accept, Authorization, CookieETag Validation
Section titled “ETag Validation”On subsequent requests with If-None-Match header matching the ETag:
HTTP/1.1 304 Not ModifiedImplementation Details
Section titled “Implementation Details”- ETag Format: Weak ETag (
W/) with base64-encoded MD5 - Applies To:
ResponseandJsonResponseonly - Excludes:
BinaryFileResponse, redirects, OPTIONS requests
flysystem-compress-adapter
Section titled “flysystem-compress-adapter”Transparent file compression at the Flysystem adapter level.
Key Features
Section titled “Key Features”- GZIP compression (level 1-9)
- Rule-based compression matching
- Fallback to uncompressed files
- Stream-based processing for large files
- Metadata tracking for original size
Configuration
Section titled “Configuration”use RightCapital\Flysystem\Compress\CompressAdapter;use RightCapital\Flysystem\Compress\Compressor\Gzip;
$rules = [ [ 'prefixes' => ['reports/', 'exports/'], 'suffixes' => ['.json', '.xml', '.csv'], 'fallback_to_origin_path' => true, ],];
$compressed = new CompressAdapter( adapter: $s3Adapter, compressor: new Gzip(level: 6), rules: $rules);// Write - automatically compresses$compressed->write('reports/data.json', json_encode($data));// Read - automatically decompresses$content = $compressed->read('reports/data.json');
// File size - returns original uncompressed size$size = $compressed->fileSize('reports/data.json');
// List contents - hides .CD.gz filesforeach ($compressed->listContents('reports', false) as $file) { echo $file->path(); // reports/data.json}Compression Rules
Section titled “Compression Rules”// Compress all with fallbackCompressAdapter::COMPRESS_ALL_WITH_FALLBACK
// Or specific rules[ 'prefixes' => ['documents/'], // Match path prefixes 'suffixes' => ['.json'], // Match file extensions 'fallback_to_origin_path' => true, // Keep original if present]Stream Processing
Section titled “Stream Processing”For large files, uses PHP stream filters to avoid memory exhaustion:
zlib.deflatefor compressionGzipBigSizefor RFC1952 compliance (>4GB files)ByteCounterfor tracking compressed size
Path Convention
Section titled “Path Convention”- Compressed files:
{original}.CD.{ext}(e.g.,data.json.CD.gz) - Hidden from directory listings
- Automatic path translation on read/write
Summary
Section titled “Summary”| Package | Cache Layer | Use Case |
|---|---|---|
| laravel-file-storage-cache | Application | Cloud storage caching |
| laravel-command-cache | Multi-layer | Cache management CLI |
| laravel-http-cache-control | HTTP | Browser/CDN caching |
| flysystem-compress-adapter | Storage | File compression |
Integration Recommendations
Section titled “Integration Recommendations”- File Storage Cache: Use when Redis unavailable but S3/cloud storage available
- Command Cache: Use in CI/CD for deployment cache cleanup
- HTTP Cache Control: Apply globally on API routes for automatic optimization
- Compress Adapter: Use for large file storage (logs, exports) to reduce costs