Cache Warming
Data Helpers uses an intelligent persistent cache system to dramatically improve performance. This guide explains how to warm up the cache before running your application or tests.
Phase 11a introduced persistent caching with automatic invalidation. The cache stores metadata about your SimpleDtos and survives PHP process restarts, making subsequent requests much faster.
Quick Start
Section titled “Quick Start”# Warm up cache (recommended)task dev:cache:warmup
# Clear cachetask dev:cache:clear
# Or use CLI scripts directlyphp bin/warm-cache.php src/Dtosphp bin/clear-cache.phpBenefits
Section titled “Benefits”- 🚀 Faster First Request: No cold start penalty
- ⚡ Improved Test Performance: Tests run ~37% faster (18.45s → 11.50s)
- 🔄 Shared Between Workers: Cache is shared across PHP-FPM workers
- 🎯 Production Ready: Warm cache during deployment
- ✅ Automatic Invalidation: Cache updates when source files change
Cache Warming Commands
Section titled “Cache Warming Commands”Task Commands (Recommended)
Section titled “Task Commands (Recommended)”The easiest way to manage cache is using the Taskfile commands:
# Warm up cache (default: PHP 8.4)task dev:cache:warmup
# Clear cachetask dev:cache:clear
# Use specific PHP versiontask dev:cache:warmup PHP=8.2task dev:cache:clear PHP=8.3
# Alias also availabletask dev:cache:warmFeatures:
- ✅ Works in Docker containers
- ✅ Automatic PHP version selection
- ✅ Beautiful colored output
- ✅ Error handling included
- ✅ Consistent with other project tasks
CLI Scripts
Section titled “CLI Scripts”You can also use the CLI scripts directly:
Warm Cache
Section titled “Warm Cache”# Warm cache for specific directoriesphp bin/warm-cache.php tests/Utils/SimpleDtos tests/Utils/Dtos
# Verbose output (shows each class)php bin/warm-cache.php -v src/Dtos
# Skip validation (faster)php bin/warm-cache.php --no-validate src/Dtos
# Show helpphp bin/warm-cache.php --helpOptions:
- -v, --verbose- Show detailed output with each class
- -q, --quiet- Suppress all output except errors
- --no-validate- Skip cache validation after warming
- -h, --help- Show help message
Clear Cache
Section titled “Clear Cache”# Clear all persistent cachephp bin/clear-cache.php
# Verbose outputphp bin/clear-cache.php -v
# Show helpphp bin/clear-cache.php --helpOptions:
- -v, --verbose- Show detailed output
- -h, --help- Show help message
Automatic Cache Warming
Section titled “Automatic Cache Warming”Test Bootstrap
Section titled “Test Bootstrap”The test suite automatically warms the cache before running tests via tests/bootstrap.php:
require_once __DIR__ . '/../vendor/autoload.php';
use event4u\DataHelpers\Console\WarmCacheCommand;
$command = new WarmCacheCommand();$directories = [    __DIR__ . '/Utils/SimpleDtos',    __DIR__ . '/Utils/Dtos',];
// Execute cache warming silently$command->execute($directories, verbose: false, validate: false);This is configured in phpunit.xml:
<phpunit bootstrap="tests/bootstrap.php" ...>Production Deployment
Section titled “Production Deployment”Add cache warming to your deployment pipeline:
# In your deployment scriptphp bin/warm-cache.php src/Dtos app/Dtos
# Or with Composer scriptscomposer dump-autoload --optimizephp bin/warm-cache.php src/DtosHow It Works
Section titled “How It Works”Cache Storage
Section titled “Cache Storage”The cache is stored in .event4u/data-helpers/cache/ by default (configurable via config/data-helpers.php).
Automatic Invalidation
Section titled “Automatic Invalidation”The cache automatically invalidates when source files change:
'cache' => [    'invalidation' => CacheInvalidation::MTIME, // or HASH, BOTH],Invalidation Strategies:
- MTIME(default): Fast, checks file modification time
- HASH: Accurate, checks file content hash (xxh128)
- BOTH: Most accurate, checks both mtime and hash
What Gets Cached
Section titled “What Gets Cached”Only SimpleDtos with:
- ✅ Valid source file (for invalidation tracking)
- ✅ Constructor parameters
- ✅ Metadata that can be extracted
Skipped:
- ❌ Abstract classes
- ❌ Classes without constructor parameters
- ❌ Classes without source file
Cache Warming Output
Section titled “Cache Warming Output”Normal Mode
Section titled “Normal Mode”━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  Data Helpers - Cache Warming━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Found 9 SimpleDto classes
........
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  Summary━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  Classes found:   9  Classes warmed:  8  Classes skipped: 1  Classes failed:  0
✅  Cache warming completed successfullyVerbose Mode
Section titled “Verbose Mode”php bin/warm-cache.php -v src/DtosShows detailed information:
- ✅ Each class warmed with parameter count
- ⚠️ Skipped classes with reason
- ❌ Failed classes with error message
- 📊 Cache validation results
Configuration
Section titled “Configuration”Cache Path
Section titled “Cache Path”<?phpreturn [    'cache' => [        'path' => './.event4u/data-helpers/cache/',    ],];Cache Driver
Section titled “Cache Driver”<?phpuse event4u\DataHelpers\Enums\CacheDriver;
return [    'cache' => [        'driver' => CacheDriver::AUTO, // AUTO, LARAVEL, SYMFONY, FILESYSTEM    ],];Auto-Detection Order:
- Laravel Cache (if available and working)
- Symfony Cache (if available and working)
- Filesystem Cache (always available)
Invalidation Strategy
Section titled “Invalidation Strategy”<?phpuse event4u\DataHelpers\Enums\CacheInvalidation;
return [    'cache' => [        'invalidation' => CacheInvalidation::MTIME, // MTIME, HASH, BOTH    ],];Performance Impact
Section titled “Performance Impact”Test Suite Performance
Section titled “Test Suite Performance”Before Cache Warming:
- Duration: 18.45s
- Cold start on every test run
After Cache Warming:
- Duration: 11.50s
- 37% faster ⚡
- Cache persists between test runs
Production Performance
Section titled “Production Performance”First Request (Cold Start):
- Without cache: ~6.1μs per DTO operation
- With warmed cache: ~4.5-5μs per DTO operation
- 20-30% faster 🚀
Subsequent Requests:
- Cache hit: ~4.5-5μs per DTO operation
- Shared between PHP-FPM workers
- Automatic invalidation on file changes
Best Practices
Section titled “Best Practices”Development
Section titled “Development”Use Task Commands (recommended for local development):
# Warm cache after pulling changesgit pulltask dev:cache:warmup
# Clear cache when debugging cache issuestask dev:cache:clear
# Warm cache with specific PHP versiontask dev:cache:warmup PHP=8.2
# Quick workflowtask dev:cache:clear && task dev:cache:warmup && task test:runWhy Task Commands?
- ✅ Works seamlessly with Docker containers
- ✅ Automatic PHP version handling
- ✅ Beautiful colored output
- ✅ Consistent with other project tasks
- ✅ Error handling included
Alternative: Direct CLI Scripts
# If not using Docker/Taskfilephp bin/warm-cache.php tests/Utils/SimpleDtosphp bin/clear-cache.phpCI/CD Pipeline
Section titled “CI/CD Pipeline”GitHub Actions:
name: Tests
on: [push, pull_request]
jobs:  test:    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v3
      - name: Setup PHP        uses: shivammathur/setup-php@v2        with:          php-version: '8.4'
      - name: Install dependencies        run: composer install --prefer-dist --no-progress
      - name: Warm cache        run: php bin/warm-cache.php tests/Utils/SimpleDtos tests/Utils/Dtos
      - name: Run tests        run: vendor/bin/pestGitLab CI:
test:  image: php:8.4  before_script:    - composer install --prefer-dist --no-progress    - php bin/warm-cache.php tests/Utils/SimpleDtos tests/Utils/Dtos  script:    - vendor/bin/pestBenefits:
- ✅ Faster test execution (37% improvement)
- ✅ Consistent cache state
- ✅ No cold start penalty
Production Deployment
Section titled “Production Deployment”Deployment Script:
#!/bin/bashset -e  # Exit on error
echo "🚀 Starting deployment..."
# Install dependenciesecho "📦 Installing dependencies..."composer install --no-dev --optimize-autoloader --no-interaction
# Warm cache for production DTOsecho "🔥 Warming cache..."php bin/warm-cache.php src/Dtos app/Dtos
# Clear OPcacheecho "🧹 Clearing OPcache..."if command -v cachetool &> /dev/null; then    cachetool opcache:reset --fcgi=/var/run/php/php8.4-fpm.sockfi
# Restart PHP-FPMecho "🔄 Restarting PHP-FPM..."sudo systemctl restart php8.4-fpm
echo "✅ Deployment complete!"Docker Deployment:
# DockerfileFROM php:8.4-fpm
# ... (other setup)
# Copy applicationCOPY . /var/www/html
# Install dependencies and warm cacheRUN composer install --no-dev --optimize-autoloader && \    php bin/warm-cache.php src/Dtos app/Dtos
# ... (rest of Dockerfile)Kubernetes Init Container:
apiVersion: apps/v1kind: Deploymentmetadata:  name: appspec:  template:    spec:      initContainers:        - name: cache-warmup          image: your-app:latest          command:            - php            - bin/warm-cache.php            - src/Dtos            - app/Dtos      containers:        - name: app          image: your-app:latestBenefits:
- ✅ No cold start on first request
- ✅ Consistent performance from start
- ✅ Cache shared between workers
- ✅ 20-30% faster first request
Troubleshooting
Section titled “Troubleshooting”Cache Not Working
Section titled “Cache Not Working”Check if cache directory is writable:
ls -la .event4u/data-helpers/cache/Cache Not Invalidating
Section titled “Cache Not Invalidating”Try using HASH or BOTH invalidation strategy:
<?phpuse event4u\DataHelpers\Enums\CacheInvalidation;
return [    'cache' => [        'invalidation' => CacheInvalidation::BOTH,    ],];Performance Not Improving
Section titled “Performance Not Improving”Verify cache is being used:
# Warm cachephp bin/warm-cache.php -v src/Dtos
# Check cache filesls -lh .event4u/data-helpers/cache/