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 Bundle Laravel Package

besimple/memcached-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require besimple/memcached-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        BeSimple\MemcachedBundle\BeSimpleMemcachedBundle::class => ['all' => true],
    ];
    
  2. Configuration Define Memcached servers in config/packages/besimple_memcached.yaml:

    besimple_memcached:
        servers:
            - host: '127.0.0.1'
              port: 11211
              weight: 1
        options:
            prefix: 'myapp_'
            compression: true
    
  3. First Use Case Inject the MemcachedClient service into a controller or service:

    use BeSimple\MemcachedBundle\Client\MemcachedClientInterface;
    
    class MyController extends AbstractController
    {
        public function __construct(private MemcachedClientInterface $memcached)
        {
        }
    
        public function cacheExample()
        {
            $this->memcached->set('key', 'value', 3600); // Cache for 1 hour
            $value = $this->memcached->get('key');
            return new Response($value ?? 'Not found');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Caching Data Use set()/get() for simple key-value caching:

    $this->memcached->set('user_123_data', $userData, 300); // 5-minute TTL
    $cachedData = $this->memcached->get('user_123_data');
    
  2. Cache Invalidation Delete keys explicitly:

    $this->memcached->delete('user_123_data');
    

    Or use wildcards (if supported by Memcached server):

    $this->memcached->deleteMulti(['user_*']);
    
  3. Tag-Based Invalidation Leverage tags for grouped invalidation (if configured):

    besimple_memcached:
        options:
            tags: true
    
    $this->memcached->add('user_123_data', $data, 300, ['user', 'profile']);
    $this->memcached->deleteByTags(['user']);
    
  4. Integration with Symfony Cache Use the bundle’s CacheAdapter for PSR-6 compliance:

    use BeSimple\MemcachedBundle\Cache\MemcachedAdapter;
    
    $cache = $this->container->get('besimple_memcached.cache.adapter');
    $item = $cache->getItem('key');
    

Advanced Patterns

  1. Fallback Logic Combine with Symfony’s CacheItemPoolInterface for fallback:

    $cache = $this->container->get('besimple_memcached.cache.adapter');
    $item = $cache->getItem('expensive_data', function (CacheItemInterface $item) {
        $item->expiresAfter(3600);
        return $this->fetchExpensiveData();
    });
    
  2. Distributed Locking Use add() with a short TTL for locks:

    $locked = $this->memcached->add('lock_key', true, 5);
    if ($locked) {
        // Critical section
        $this->memcached->delete('lock_key');
    }
    
  3. Batch Operations Fetch multiple keys at once:

    $keys = ['key1', 'key2', 'key3'];
    $values = $this->memcached->getMulti($keys);
    

Gotchas and Tips

Common Pitfalls

  1. Connection Issues

    • Symptom: Silent failures or timeouts.
    • Fix: Verify servers config and test connectivity:
      telnet 127.0.0.1 11211
      
    • Ensure the Memcached server is running and accessible.
  2. Key Collisions

    • Symptom: Unexpected data overwrites due to missing prefixes.
    • Fix: Always use the prefix in config (e.g., myapp_) to namespace keys.
  3. TTL Misconfiguration

    • Symptom: Data expires too soon or persists indefinitely.
    • Fix: Use explicit TTLs (e.g., 3600 for 1 hour) and avoid 0 (unlimited).
  4. Serialization Errors

    • Symptom: Complex objects fail to cache.
    • Fix: Implement __serialize()/__unserialize() or use json_encode():
      $this->memcached->set('obj', json_encode($object));
      $data = json_decode($this->memcached->get('obj'), true);
      

Debugging Tips

  1. Enable Logging Add to config/packages/monolog.yaml:

    handlers:
        memcached:
            type: fingers_crossed
            action_level: error
            handler: nested
            buffer_size: 100
            channels: ["besimple_memcached"]
    
  2. Check Stats Use the stats() method to monitor server health:

    $stats = $this->memcached->getStats();
    
  3. Test Locally Run Memcached in Docker for development:

    docker run -p 11211:11211 memcached
    

Extension Points

  1. Custom Client Configuration Override the default client in config/packages/besimple_memcached.yaml:

    besimple_memcached:
        client_class: App\Service\CustomMemcachedClient
    
  2. Event Listeners Subscribe to MemcachedEvents (if the bundle supports them) for pre/post-cache operations:

    // config/services.yaml
    App\EventListener\MemcachedListener:
        tags:
            - { name: kernel.event_listener, event: besimple_memcached.cache.set, method: onCacheSet }
    
  3. Proxy Integration Use with Symfony’s HttpCache or ProxyClient for HTTP caching:

    $client = new ProxyClient(
        new MemcachedAdapter($this->memcached),
        new Client()
    );
    
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