Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Do File Cache Psr 6 Laravel Package

jord-jd/do-file-cache-psr-6

PSR-6 cache adapter for Jord-JD/DO File Cache. Use it to access DO File Cache through standard PSR-6 CacheItemPoolInterface for framework-agnostic caching with Composer-based installation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Require the package via Composer:

    composer require jord-jd/do-file-cache-psr-6 do/file-cache
    
    • Note: The do/file-cache dependency is required but not auto-installed. Add it explicitly.
  2. Configure Laravel Update config/cache.php to include the new store:

    'stores' => [
        'do_file' => [
            'driver' => 'do_file',
            'path'   => env('DO_CACHE_PATH', storage_path('framework/cache/do')),
            'prefix' => env('DO_CACHE_PREFIX', 'do_'),
            'key'    => env('DO_SPACES_KEY'),
            'secret' => env('DO_SPACES_SECRET'),
            'region' => env('DO_SPACES_REGION', 'nyc3'),
        ],
    ],
    

    Add DO-specific environment variables to .env:

    DO_SPACES_KEY=your_key
    DO_SPACES_SECRET=your_secret
    DO_SPACES_REGION=nyc3
    DO_CACHE_PATH=storage/framework/cache/do
    
  3. First Use Case: Replace File Cache Driver Update your cache calls to use the new driver:

    // Before (default file cache)
    Cache::remember('key', 60, function () { return expensiveOperation(); });
    
    // After (DO File Cache)
    Cache::store('do_file')->remember('key', 60, function () { return expensiveOperation(); });
    

Implementation Patterns

Usage Patterns

  1. PSR-6 Compliance Use the package’s CacheItemPoolInterface directly for low-level control:

    $cache = app('cache.store.do_file');
    $item = $cache->getItem('key');
    if (!$item->isHit()) {
        $item->set(expensiveOperation());
        $item->expiresAfter(3600);
        $cache->save($item);
    }
    
  2. Laravel Cache Facade Integration Leverage Laravel’s facade for consistency:

    // Get cached data
    $data = Cache::store('do_file')->get('key');
    
    // Set cached data
    Cache::store('do_file')->put('key', $data, 3600);
    
    // Tagged caching
    Cache::store('do_file')->tags(['users'])->put('user:1', $userData);
    
  3. Fallback Strategy Implement a fallback to another cache driver (e.g., Redis) if DO File Cache fails:

    $cache = Cache::store('do_file');
    if (!$cache->get('key')) {
        $fallbackCache = Cache::store('redis');
        $data = $fallbackCache->get('key') ?: expensiveOperation();
        $cache->put('key', $data, 3600);
    }
    
  4. Cache Warming Preload critical caches during application boot:

    public function boot()
    {
        $this->app->booted(function () {
            Cache::store('do_file')->remember('homepage_data', 3600, function () {
                return HomepageData::fetch();
            });
        });
    }
    
  5. Dynamic Cache Driver Switching Use environment variables to switch between cache drivers:

    $driver = env('CACHE_DRIVER', 'do_file');
    $cache = Cache::store($driver);
    

Integration Tips

  • Tag-Based Invalidation Use tags for grouped cache invalidation (e.g., when a user updates their profile):

    Cache::store('do_file')->tags(['user:1'])->flush();
    
  • Cache Events Listen for cache events (e.g., Cache::store('do_file')->getEventDispatcher()) to log or react to cache hits/misses:

    Cache::store('do_file')->getEventDispatcher()->addListener(
        'CacheItemPool::miss',
        function ($args) {
            Log::debug('Cache miss for key: ' . $args['key']);
        }
    );
    
  • Custom Cache Keys Override the default key prefix to avoid collisions:

    Cache::store('do_file')->setPrefix('app_');
    
  • Testing Mock the CacheItemPoolInterface in tests:

    $mockCache = Mockery::mock('overload:\Psr\Cache\CacheItemPoolInterface');
    $mockCache->shouldReceive('getItem')->andReturnUsing(function ($key) {
        return new \Psr\Cache\CacheItem($key, false);
    });
    $this->app->instance('cache.store.do_file', $mockCache);
    

Gotchas and Tips

Pitfalls

  1. DO Infrastructure Dependency

    • The package assumes DigitalOcean’s filesystem cache (e.g., Spaces, Droplets). If your app isn’t on DO, performance may degrade due to network latency.
    • Workaround: Use a local filesystem path (e.g., storage_path('framework/cache/do')) if DO-specific features aren’t needed.
  2. Concurrency Issues

    • DO File Cache may not handle high concurrency as well as Redis or Memcached. Under heavy load, race conditions can occur.
    • Workaround: Use Laravel’s Cache::lock() for critical sections or implement a retry mechanism:
      Cache::store('do_file')->lock('key', 5, function () {
          // Critical section
      });
      
  3. Cache Invalidation Delays

    • Tagged invalidation may not be instantaneous across distributed DO regions.
    • Workaround: Use a queue job to flush tags asynchronously:
      Cache::store('do_file')->tags(['users'])->flush();
      dispatch(new FlushDoFileCacheTags(['users']));
      
  4. Credential Management

    • Hardcoding DO API keys in .env can be risky. Ensure credentials are rotated regularly.
    • Workaround: Use a secrets manager (e.g., HashiCorp Vault) and fetch credentials dynamically.
  5. Laravel Version Mismatches

    • The package may not support the latest Laravel features (e.g., PSR-6 enhancements in Laravel 10).
    • Workaround: Check the package’s composer.json for Laravel version constraints and test thoroughly.
  6. Cold Start Latency

    • First-time cache misses may be slower due to DO’s filesystem initialization.
    • Workaround: Pre-warm critical caches during deployment:
      php artisan cache:warm
      

Debugging

  1. Enable Debug Logging Add debug logging for cache operations:

    Cache::store('do_file')->extend('do_file', function ($app) {
        return new class($app['cache.do_file.store']) extends \Illuminate\Cache\Repository {
            public function get($key, $default = null) {
                $result = parent::get($key, $default);
                \Log::debug("DO Cache Hit: {$key}", ['hit' => $result !== $default]);
                return $result;
            }
        };
    });
    
  2. Check DO Filesystem Permissions Ensure the DO filesystem (or local path) is writable:

    chmod -R 775 storage/framework/cache/do
    
  3. Validate DO Credentials Test DO API connectivity separately:

    use DO\FileCache\Client;
    $client = new Client(env('DO_SPACES_KEY'), env('DO_SPACES_SECRET'));
    $client->ping(); // Check connectivity
    
  4. Monitor Cache Hit/Miss Ratios Use Laravel’s cache:clear logs or a custom middleware to track performance:

    Cache::store('do_file')->getEventDispatcher()->addListener(
        'CacheItemPool::miss',
        function ($args) {
            \Log::warning("Cache miss for key: {$args['key']}");
        }
    );
    

Tips

  1. Use for Read-Heavy Workloads DO File Cache excels at read-heavy scenarios (e.g., API responses, template fragments). Avoid using it for write-heavy operations.

  2. Combine with Other Drivers Use DO File Cache as a fallback or secondary cache:

    $primaryCache = Cache::store('redis');
    $fallbackCache = Cache::store('do_file');
    
    $data = $primaryCache->get('key') ?: $fallbackCache->get('key');
    
  3. Optimize Cache Expiry Set appropriate TTLs to balance freshness and performance:

    // Short TTL for volatile data
    Cache::store('do_file')->put('volatile_data', $data, 60);
    
    // Long TTL for static data
    Cache::store('do_file')->put('static_data', $data, 86400);
    
  4. Leverage DO’s Global Filesystem If using DO Spaces, leverage its global CDN for faster reads:

    Cache::store('do_file')->
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor