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

Memcached Adapter Laravel Package

cache/memcached-adapter

PSR-6 cache pool backed by Memcached. Create a Memcached client, add servers, and use MemcachedCachePool for fast, standards-based caching. Part of the PHP Cache ecosystem with shared docs for tagging and hierarchy support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require cache/memcached-adapter
    
  2. Basic Configuration (in config/cache.php):
    'memcached' => [
        'driver' => 'memcached',
        'servers' => [
            [
                'host' => 'localhost',
                'port' => 11211,
                'weight' => 100,
            ],
        ],
        'options' => [
            'prefix' => 'laravel_', // Avoid key collisions
            'compression' => true,  // Enable for large payloads
        ],
    ],
    
  3. First Use Case:
    use Illuminate\Support\Facades\Cache;
    
    // Store with TTL (10 minutes)
    Cache::put('user:123', ['name' => 'John'], 600);
    
    // Retrieve
    $user = Cache::get('user:123');
    
    // Tag-based invalidation (if using tags)
    Cache::tags('users')->remember('user:123', 600, fn() => ['name' => 'John']);
    

Where to Look First

  • Laravel Integration: Check vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php for built-in Memcached support.
  • PSR-6 Docs: php-cache.org for advanced features like tagging and hierarchy.
  • Memcached Client: Review \Memcached options (e.g., sasl_auth_data, retry_timeout) in the Memcached PHP docs.

Implementation Patterns

Workflows

  1. Tag-Based Caching (Laravel Example):

    // Cache user data with tags
    Cache::tags(['users', 'premium'])->put('user:123', $userData, now()->addHour());
    
    // Invalidate by tag (e.g., after user update)
    Cache::tags('users')->flush();
    
    • Use Case: E-commerce product listings, user sessions, or multi-tenant data.
  2. Hierarchical Caching (Fallback to Redis):

    $pool = new \Cache\Adapter\Memcached\MemcachedCachePool(
        $memcachedClient,
        ['fallback' => new \Cache\Adapter\Redis\RedisCachePool($redisClient)]
    );
    
    • Use Case: High-availability setups where Memcached is primary but Redis acts as a backup.
  3. Batch Operations:

    // Delete multiple keys at once
    Cache::forget(['user:1', 'user:2', 'user:3']);
    
    // Get multiple keys (PSR-6 `getItems`)
    $items = Cache::many(['user:1', 'user:2']);
    
    • Use Case: Clearing cached reports or invalidating related records.

Integration Tips

  • Laravel Cache Manager: Bind the adapter in config/cache.php:

    'connections' => [
        'memcached' => [
            'driver' => 'memcached',
            'servers' => [...],
            'options' => [...],
        ],
    ],
    

    Then use Cache::store('memcached')->....

  • Dependency Injection:

    public function __construct(private MemcachedCachePool $cache) {}
    

    Register the pool in AppServiceProvider:

    $this->app->bind(MemcachedCachePool::class, function ($app) {
        $client = new \Memcached();
        $client->addServer(...);
        return new MemcachedCachePool($client);
    });
    
  • Event Listeners: Use Cache::tags('users')->flush() in UserUpdated event listeners to invalidate cached user data.


Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • Issue: Without a prefix, keys may clash with other services using Memcached.
    • Fix: Always set 'prefix' => 'laravel_' (or a unique namespace) in config.
  2. Connection Failures:

    • Issue: Memcached client throws MemcachedException if servers are unreachable.
    • Fix: Implement retry logic or use a fallback pool:
      $pool = new MemcachedCachePool($client, [
          'fallback' => new NullCachePool(), // Graceful degradation
      ]);
      
  3. Large Payloads:

    • Issue: Memcached has a 1MB item size limit (configurable via max_item_size).
    • Fix: Enable compression ('compression' => true) or serialize data to reduce size.
  4. Tagging Limitations:

    • Issue: Tags are not natively supported by Memcached; this adapter emulates them via key prefixes.
    • Fix: Avoid excessive tags (e.g., >100) to prevent key explosion.
  5. TTL Granularity:

    • Issue: Memcached TTL is in seconds (floats are truncated).
    • Fix: Round TTL values to avoid premature expiration:
      $ttl = ceil(now()->diffInSeconds($expiryTime));
      

Debugging

  • Check Server Status:
    $client->getStats(); // Inspect Memcached server health
    
  • Enable Logging:
    $client->setOption(\Memcached::OPT_LOGGING, true);
    $client->setOption(\Memcached::OPT_DEBUG, 32767); // Verbose logging
    
  • Key Inspection: Use Cache::store('memcached')->getItemMetadata('key') to debug TTL/flags.

Extension Points

  1. Custom Item Class: Override Cache\Taggable\TaggedCacheItem for custom metadata:

    class CustomCacheItem extends TaggedCacheItem {
        public function getCustomField() { ... }
    }
    

    Pass it to the pool constructor:

    new MemcachedCachePool($client, [], CustomCacheItem::class);
    
  2. Event Subscribers: Extend Cache\Event\EventEmitter to hook into beforeGet, afterSet, etc.:

    $pool->addEventSubscriber(new class implements EventSubscriber {
        public function onBeforeGet(Item $item) { ... }
    });
    
  3. Pool Wrappers: Create a decorator for cross-cutting concerns (e.g., logging, metrics):

    class LoggingCachePool implements CacheItemPoolInterface {
        public function __construct(private CacheItemPoolInterface $pool) {}
    
        public function getItem($key) {
            Log::debug("Fetching key: $key");
            return $this->pool->getItem($key);
        }
        // Delegate other methods...
    }
    

Configuration Quirks

  • Weighted Servers: Use 'weight' in server config to distribute load (e.g., ['weight' => 50] for half the traffic).
  • SASL Authentication: Enable for secure clusters:
    $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
    $client->setSaslAuthData('username', 'password');
    
  • Persistent Connections: Reduce overhead with:
    $client->setOption(\Memcached::OPT_PERSISTENT, true);
    
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