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

Cache Laravel Package

zetacomponents/cache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require zetacomponents/cache
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        ZetaComponents\Cache\Cache::class,
    ],
    
  2. Basic Usage Initialize a cache backend (e.g., file-based):

    use ZetaComponents\Cache\Cache;
    
    $cache = new Cache('file', [
        'cacheDir' => storage_path('app/cache'),
    ]);
    
  3. First Use Case: Storing & Retrieving Data

    // Store data (expires in 3600 seconds)
    $cache->set('key', 'value', 3600);
    
    // Retrieve data
    $value = $cache->get('key'); // Returns 'value' or false if not found
    
  4. Key Locations

    • Documentation: Check the Zeta Components Wiki (if available) or source comments.
    • Source Code: Focus on ZetaComponents/Cache/ for backends (File.php, Memcache.php, etc.) and core logic.

Implementation Patterns

Common Workflows

  1. Multi-Backend Caching Use different backends for different needs (e.g., file for dev, memcache for prod):

    $devCache = new Cache('file', ['cacheDir' => storage_path('app/cache')]);
    $prodCache = new Cache('memcache', ['servers' => ['localhost:11211']]);
    
  2. Automatic Expiration Leverage set() with a timestamp for manual expiration:

    $cache->set('key', 'value', time() + 3600); // Expires in 1 hour
    
  3. Cache Invalidation Delete keys explicitly:

    $cache->delete('key');
    

    Or clear the entire cache (backend-dependent):

    $cache->clear();
    
  4. Tag-Based Caching (Advanced) Use set() with tags (if supported by the backend) for grouped invalidation:

    $cache->set('user:123', $userData, 3600, ['users']);
    $cache->deleteByTag('users'); // Invalidate all tagged keys
    

Integration Tips

  • Laravel Integration Bind the cache to Laravel’s container for dependency injection:

    $app->singleton('cache', function () {
        return new Cache('file', ['cacheDir' => storage_path('app/cache')]);
    });
    

    Then inject via constructor:

    public function __construct(private Cache $cache) {}
    
  • Middleware for Cached Responses Use the cache to store full HTTP responses (e.g., API results):

    $response = $cache->get('api:users');
    if (!$response) {
        $response = Http::get('https://api.example.com/users');
        $cache->set('api:users', $response, 3600);
    }
    
  • Fallback Logic Combine with Laravel’s cache system for redundancy:

    $value = $cache->get('key') ?: Cache::get('key');
    

Gotchas and Tips

Pitfalls

  1. No Built-in Laravel Support

    • The package lacks native Laravel integration (e.g., no Cache::store() compatibility).
    • Workaround: Wrap it in a facade or service class to mimic Laravel’s Cache API.
  2. Backend-Specific Quirks

    • File Cache: Directory must be writable. Use storage_path('app/cache') and ensure permissions:
      mkdir -p storage/app/cache && chmod -R 775 storage/app/cache
      
    • Memcache/Redis: Requires PHP extensions (memcache, redis) and server setup. Test connections early:
      try {
          $cache = new Cache('memcache', ['servers' => ['localhost:11211']]);
      } catch (\Exception $e) {
          Log::error('Cache server unreachable: ' . $e->getMessage());
      }
      
  3. No Automatic Tagging

    • Unlike Laravel’s cache, this package doesn’t natively support tags. Implement a custom layer if needed:
      class TaggedCache {
          public function set($key, $value, $ttl, array $tags) {
              $this->cache->set($key, $value, $ttl);
              foreach ($tags as $tag) {
                  $this->cache->set("tag:$tag:$key", 1, $ttl);
              }
          }
          public function deleteByTag($tag) {
              $keys = $this->cache->get("tag:$tag:*");
              // ... delete each key
          }
      }
      
  4. Serialization Issues

    • Complex objects (e.g., closures, resources) may not serialize properly. Use serialize()/unserialize():
      $cache->set('key', serialize($complexObject));
      $object = unserialize($cache->get('key'));
      
  5. No Cache Events

    • Unlike Laravel, this package doesn’t emit events on cache hits/misses. Log manually if needed:
      if ($cache->get('key')) {
          Log::debug('Cache hit for key: key');
      }
      

Debugging Tips

  1. Check Backend Status Verify the backend is working:

    if (!$cache->isSupported()) {
        throw new \RuntimeException('Unsupported cache backend');
    }
    
  2. Inspect Cache Contents List all keys (file backend only):

    $keys = $cache->getKeys(); // If supported
    // Or manually scan the directory
    
  3. Handle Exceptions Wrap cache operations in try-catch:

    try {
        $value = $cache->get('key');
    } catch (\Exception $e) {
        Log::error('Cache error: ' . $e->getMessage());
        // Fallback to database or other source
    }
    

Extension Points

  1. Custom Backends Extend ZetaComponents\Cache\Backend to create new storage adapters (e.g., DynamoDB, S3):

    class S3CacheBackend extends Backend {
        public function get($key) { /* ... */ }
        public function set($key, $value, $ttl) { /* ... */ }
        // ...
    }
    
  2. Decorators for Logging/Metrics Wrap the cache to add functionality:

    class LoggingCache {
        public function __construct(private Cache $cache) {}
        public function get($key) {
            $start = microtime(true);
            $value = $this->cache->get($key);
            Log::debug("Cache get($key) took " . (microtime(true) - $start) . "s");
            return $value;
        }
    }
    
  3. Fallback Chain Implement a chain of caches (e.g., try memcache, fall back to file):

    class FallbackCache {
        public function __construct(private array $backends) {}
        public function get($key) {
            foreach ($this->backends as $backend) {
                if ($value = $backend->get($key)) {
                    return $value;
                }
            }
            return false;
        }
    }
    
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