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

Void Adapter Laravel Package

cache/void-adapter

PSR-6 “void” (null/blackhole) cache pool that never stores anything and always returns empty cache items. Useful for disabling caching in tests or no-op environments. Part of the PHP-Cache organization.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require cache/void-adapter
    

    No additional configuration is required.

  2. First Use Case: Replace any PSR-6 cache pool with VoidCachePool for testing or debugging:

    use Cache\VoidCachePool;
    
    $cache = new VoidCachePool();
    $item = $cache->getItem('test-key');
    $item->set('value'); // Data is discarded immediately
    $cache->save($item);  // No-op
    
  3. Laravel Integration: Register as a custom driver in config/cache.php:

    'void' => [
        'driver' => 'cache',
        'pool' => Cache\VoidCachePool::class,
    ],
    

    Use via:

    Cache::driver('void')->put('key', 'value'); // Silent no-op
    

Where to Look First

  • PSR-6 Compliance: Verify all methods (getItem, save, deleteItem, etc.) work as expected (they do, but return empty results).
  • Laravel Cache Facade: Test with Cache::driver('void')->remember() to confirm no persistence.
  • Tag Support: Confirm getItemsByTag() returns empty results (expected behavior).

Implementation Patterns

Usage Patterns

  1. Debugging Workflows:

    • Temporarily switch to void in AppServiceProvider during debugging:
      if (app()->environment('debug')) {
          Cache::extend('void', fn() => new VoidCachePool());
          Cache::setDefaultDriver('void');
      }
      
  2. Feature Flag Isolation:

    • Use for experimental features to avoid cache pollution:
      if (Feature::isEnabled('experimental-feature')) {
          Cache::driver('void')->put('feature-data', $data);
      }
      
  3. Fallback Strategy:

    • Implement a circuit breaker for Redis failures:
      try {
          return Cache::driver('redis')->get('key');
      } catch (RedisException $e) {
          return Cache::driver('void')->get('key'); // Fallback
      }
      
  4. Test Environments:

    • Force void in phpunit.xml:
      <env name="CACHE_DRIVER" value="void"/>
      

Workflows

  1. Cache-Agnostic Development:

    • Write cache-dependent logic without worrying about persistence:
      $cache = Cache::driver('void'); // Works identically to Redis/APCu
      $data = $cache->get('key', fn() => fetchExpensiveData());
      
  2. Dynamic Driver Switching:

    • Use environment variables to toggle caching:
      $driver = env('CACHE_DRIVER', 'redis');
      Cache::driver($driver)->put('key', 'value');
      
  3. Tagging (Limited Use):

    • Use tags for organizational purposes (though they won’t persist):
      Cache::driver('void')->tags(['analytics'])->put('report', $data);
      

Integration Tips

  1. Laravel Cache Events:

    • Listen for cache events to log void usage:
      Cache::store('void')->listen(function ($events) {
          Log::debug('Void cache event triggered:', $events);
      });
      
  2. Service Container Binding:

    • Bind VoidCachePool as a singleton for dependency injection:
      $app->singleton(Cache\VoidCachePool::class, fn() => new VoidCachePool());
      
  3. Hybrid Caching:

    • Combine with other drivers for selective caching:
      $cache = Cache::driver('redis');
      if (app()->environment('local')) {
          $cache = Cache::driver('void'); // Override locally
      }
      
  4. Cache Tagging in Laravel:

    • Use Cache::tags() with void for testing tag-based invalidation logic:
      Cache::tags(['users'])->put('user:1', $user);
      Cache::tags(['users'])->flush(); // No-op, but tests pass
      

Gotchas and Tips

Pitfalls

  1. Silent Data Loss:

    • All writes are discarded. Never use in production unless explicitly as a fallback.
    • Tip: Add a middleware to log warnings:
      if (app()->environment('production') && Cache::getStore()->getDriver() === 'void') {
          Log::warning('Void cache detected in production!');
      }
      
  2. Tagging Misuse:

    • Methods like getItemsByTag() return empty results, which may break logic assuming tags work.
    • Tip: Document tagging limitations in your codebase.
  3. Laravel-Specific Issues:

    • Event Caching: Events cached with void will not persist across requests.
    • Queue Jobs: Job payloads cached with void will not survive worker restarts.
    • Tip: Avoid using void for critical Laravel features like event caching.
  4. Performance Metrics:

    • All operations report as "cache misses," skewing monitoring data.
    • Tip: Exclude void from cache analytics in production.
  5. Accidental Deployment:

    • Ensure void is never the default driver in config/cache.php for production.
    • Tip: Use environment-specific configs:
      // config/cache.php
      'default' => env('CACHE_DRIVER', 'redis'),
      

Debugging

  1. Verify No Persistence:

    • Check if data is actually lost:
      Cache::driver('void')->put('test', 'value');
      $this->assertNull(Cache::driver('void')->get('test'));
      
  2. Tagging Debugging:

    • Test tag-related methods:
      Cache::driver('void')->tags(['test'])->put('key', 'value');
      $this->assertEmpty(Cache::driver('void')->getItemsByTag('test'));
      
  3. Laravel Cache Events:

    • Debug event listeners:
      Cache::store('void')->listen(function ($events) {
          dd($events); // Inspect triggered events
      });
      

Configuration Quirks

  1. PSR-6 Compliance:

    • While fully compliant, some methods (e.g., getMetadata) return empty results.
    • Tip: Override the pool if custom behavior is needed:
      class CustomVoidCachePool extends VoidCachePool {
          public function getMetadata($key) {
              return new CacheItemMetadata(); // Return empty metadata
          }
      }
      
  2. Laravel Cache Manager:

    • Ensure the driver is properly registered:
      Cache::extend('void', fn() => new VoidCachePool());
      
    • Tip: Use Cache::driver('void') instead of Cache::store('void') for clarity.
  3. Environment-Specific Drivers:

    • Dynamically switch drivers based on environment:
      $driver = app()->environment('local') ? 'void' : 'redis';
      Cache::driver($driver)->put('key', 'value');
      

Extension Points

  1. Custom Void Pool:

    • Extend VoidCachePool to add logging or mock behavior:
      class LoggingVoidCachePool extends VoidCachePool {
          public function save(CacheItemInterface $item) {
              Log::debug("Void save called for key: {$item->getKey()}");
              parent::save($item);
          }
      }
      
  2. Hybrid Cache Logic:

    • Combine with other drivers for conditional caching:
      $cache = Cache::driver('void');
      if (app()->environment('production')) {
          $cache = Cache::driver('redis');
      }
      
  3. Tagging Simulation:

    • Mock tag behavior for testing:
      $mockTags = ['users', 'reports'];
      $cache = new class extends VoidCachePool {
          public function getItemTags($key) {
              return $mockTags;
          }
      };
      
  4. Fallback with Retry:

    • Implement a retry mechanism for transient cache failures:
      function getWithFallback($key, callable $callback) {
          try {
              return Cache::driver('redis')->get($key);
          } catch (Exception $e) {
              return Cache::driver('void')->get($key, $callback);
          }
      }
      
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.
terminal42/code-quality-tools
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