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

Memcache Adapter Laravel Package

cache/memcache-adapter

PSR-6 cache pool implementation backed by the Memcache extension. Create a Memcache client, connect to your server, and use MemcacheCachePool for standards-based caching. Part of the PHP Cache (php-cache) ecosystem.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package:
    composer require cache/memcache-adapter
    
  2. Configure Laravel’s Cache Manager (config/cache.php):
    'stores' => [
        'memcache' => [
            'driver' => 'memcache',
            'connection' => 'memcache',
            'prefix' => 'laravel_',
        ],
    ],
    
  3. Define the Memcache connection in .env:
    CACHE_CONNECTIONS_memcache_driver=memcache
    CACHE_CONNECTIONS_memcache_host=127.0.0.1
    CACHE_CONNECTIONS_memcache_port=11211
    
  4. Extend Laravel’s Cache Manager (in a service provider):
    Cache::extend('memcache', function ($app) {
        $memcache = new \Memcache();
        $memcache->connect(env('MEMCACHE_HOST', '127.0.0.1'), env('MEMCACHE_PORT', 11211));
        return new \Cache\MemcacheAdapter\MemcacheCachePool($memcache);
    });
    
  5. Use the cache via Laravel’s facade:
    Cache::put('key', 'value', now()->addMinutes(10));
    $value = Cache::get('key');
    

First Use Case: Caching API Responses

// In a controller or service
$response = Cache::remember('api_users', now()->addHours(1), function () {
    return Http::get('https://api.example.com/users')->json();
});
return response()->json($response);

Implementation Patterns

Workflow: Tag-Based Invalidation

Leverage Memcache’s tagging for bulk invalidation (e.g., user-specific cache):

// Store with tags
Cache::tags(['user:123'])->put('user_profile_123', $profileData, now()->addHours(1));

// Invalidate by tag (e.g., after user update)
Cache::tags(['user:123'])->flush();

Integration with Laravel Events

Listen for model events to invalidate cache:

// In EventServiceProvider
protected $listen = [
    'App\Events\UserUpdated' => [
        'CacheInvalidationHandler',
    ],
];

// Handler
public function handle(UserUpdated $event) {
    Cache::tags(['user:' . $event->user->id])->flush();
}

Multi-Cache Strategy

Combine Memcache (for hot data) with Redis (for persistence):

// In config/cache.php
'stores' => [
    'memcache' => [
        'driver' => 'memcache',
        'connection' => 'memcache',
    ],
    'redis' => [
        'driver' => 'redis',
        'connection' => 'redis',
    ],
],

// In a service
public function getData() {
    $data = Cache::store('memcache')->get('hot_data');
    if (!$data) {
        $data = Cache::store('redis')->get('fallback_data');
    }
    return $data;
}

Connection Management

Reuse Memcache connections for efficiency:

// In a service provider
public function boot() {
    $memcache = new \Memcache();
    $memcache->connect(env('MEMCACHE_HOST'), env('MEMCACHE_PORT'));

    Cache::extend('memcache', function () use ($memcache) {
        return new \Cache\MemcacheAdapter\MemcacheCachePool($memcache);
    });
}

Batch Operations

Use PSR-6’s getItems() and deleteItems() for bulk operations:

// Get multiple items
$items = Cache::many(['key1', 'key2', 'key3']);

// Delete multiple items
Cache::forget(['key1', 'key2']);

Gotchas and Tips

Pitfalls

  1. Extension Dependency:

    • Requires ext-memcache (not memcached). Verify availability:
      php -m | grep memcache
      
    • Fix: Use ext-memcached or advocate for migration to Redis.
  2. Tagging Limitations:

    • Laravel’s Cache::tags() may not work out-of-the-box. Implement a wrapper:
      Cache::extend('memcache', function () {
          $pool = new MemcacheCachePool(new \Memcache());
          return new class($pool) implements \Illuminate\Contracts\Cache\TaggableStore {
              // Implement tagging methods
          };
      });
      
  3. Serialization Issues:

    • Memcache has a 1MB item size limit. Large objects (e.g., closures, complex arrays) may fail.
    • Fix: Use serialize()/unserialize() or store references.
  4. Connection Failures:

    • Memcache is stateless; connection drops can cause silent failures.
    • Fix: Implement retry logic:
      Cache::remember('key', now()->addMinutes(5), function () {
          return withRetry(3, function () {
              return $expensiveOperation();
          });
      });
      
  5. TTL Granularity:

    • Memcache uses seconds for TTL. Laravel’s now()->addMinutes() may lose precision.
    • Fix: Convert to seconds explicitly:
      Cache::put('key', 'value', ceil(now()->addMinutes(10)->timestamp));
      

Debugging Tips

  1. Inspect the Underlying Pool:

    $pool = Cache::store('memcache')->getStore();
    var_dump($pool->getItem('key')->isHit());
    
  2. Check Memcache Stats:

    $memcache = Cache::store('memcache')->getStore()->getClient();
    var_dump($memcache->getStats());
    
  3. Enable Memcache Logging:

    $memcache = new \Memcache();
    $memcache->setOption(\Memcache::OPT_DEBUG, 3);
    

Configuration Quirks

  1. Prefix Collisions:

    • Ensure Laravel’s cache prefix (laravel_) doesn’t conflict with other apps sharing the Memcache instance.
    • Fix: Customize the prefix in config/cache.php.
  2. Case Sensitivity:

    • Memcache keys are case-sensitive. Use consistent casing:
      Cache::put('UserProfile', $data); // Avoid 'userprofile'
      
  3. Default TTL:

    • PSR-6’s null TTL (forever) may not work as expected. Use 0 for no expiration:
      Cache::put('key', 'value', 0); // No expiration
      

Extension Points

  1. Custom Cache Item: Override MemcacheCacheItem for custom serialization:

    class CustomMemcacheItem extends \Cache\MemcacheAdapter\MemcacheCacheItem {
        public function get() {
            $data = parent::get();
            return json_decode($data, true);
        }
    }
    
  2. Pool Decorator: Add middleware to the MemcacheCachePool:

    $pool = new MemcacheCachePool($memcache);
    $pool = new class($pool) implements \Psr\Cache\CacheItemPoolInterface {
        public function getItem($key) {
            $item = $this->pool->getItem($key);
            // Add custom logic (e.g., logging, compression)
            return $item;
        }
        // Delegate other methods to $this->pool
    };
    
  3. Fallback Mechanism: Implement a fallback to another cache store:

    Cache::extend('memcache_fallback', function () {
        $memcachePool = new MemcacheCachePool(new \Memcache());
        $redisPool = new \Cache\RedisAdapter\RedisCachePool(new \Redis());
        return new class($memcachePool, $redisPool) implements \Psr\Cache\CacheItemPoolInterface {
            public function getItem($key) {
                try {
                    return $this->memcachePool->getItem($key);
                } catch (\Exception $e) {
                    return $this->redisPool->getItem($key);
                }
            }
            // Implement other methods
        };
    });
    

Performance Tips

  1. Connection Pooling: Reuse the Memcache connection across requests to avoid overhead:

    // In a singleton service
    public function getCachePool() {
        static $pool;
        if (!$pool) {
            $memcache = new \Memcache();
            $memcache->connect(env('MEMCACHE_HOST'), env('MEMCACHE_PORT'));
            $pool = new MemcacheCachePool($memcache);
        }
        return $pool;
    }
    
  2. Compress Large Data: Use gzip for large cache values:

    Cache::put('key', gzcompress($data), now()->addHours(1));
    // Retrieve
    $data = gzuncompress(Cache::get('key'));
    
  3. Avoid Blocking Calls: Offload cache

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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