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

druidvav/memcache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony project via Composer:

    composer require druidvav/memcache-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Druidvav\MemcacheBundle\DruidvavMemcacheBundle::class => ['all' => true],
    ];
    
  2. Configuration Define Memcache connection in config/packages/druidvav_memcache.yaml:

    druidvav_memcache:
        servers:
            default:
                host: '127.0.0.1'
                port: 11211
                weight: 1
    
  3. First Use Case Inject the MemcacheClient service and use it to cache a simple value:

    use Druidvav\MemcacheBundle\Client\MemcacheClient;
    
    class MyService
    {
        public function __construct(private MemcacheClient $memcache)
        {
        }
    
        public function getCachedData()
        {
            $key = 'my_key';
            $value = $this->memcache->get($key);
    
            if ($value === false) {
                $value = $this->fetchFromDatabase(); // Fallback logic
                $this->memcache->set($key, $value, 3600); // Cache for 1 hour
            }
    
            return $value;
        }
    }
    

Implementation Patterns

Common Workflows

  1. Caching Database Queries Use Memcache to reduce database load for repeated queries:

    $cacheKey = 'user_' . $userId;
    $user = $this->memcache->get($cacheKey);
    
    if (!$user) {
        $user = $this->userRepository->find($userId);
        $this->memcache->set($cacheKey, $user, 300); // Cache for 5 minutes
    }
    
  2. Fragment Caching Cache parts of a Symfony Twig template:

    {% cache 'sidebar_' ~ app.user.id (app.user) %}
        {% include 'partials/sidebar.html.twig' %}
    {% endcache %}
    

    Note: Requires additional setup for Memcache-backed cache pool in Symfony.

  3. Distributed Caching Use the same Memcache instance across multiple application servers for shared caching:

    # config/packages/druidvav_memcache.yaml
    druidvav_memcache:
        servers:
            distributed:
                host: 'memcache-cluster'
                port: 11211
                weight: 2
    
  4. TTL Management Dynamically set Time-To-Live (TTL) based on data volatility:

    $ttl = $isFrequentlyUpdated ? 60 : 3600; // 1 min or 1 hour
    $this->memcache->set($key, $data, $ttl);
    

Integration Tips

  • Symfony Cache Adapter Use the bundle’s adapter to integrate with Symfony’s CacheInterface:

    $cache = $this->memcache->getAdapter();
    $item = $cache->getItem('some_key');
    
  • Dependency Injection Prefer constructor injection for MemcacheClient to ensure testability:

    public function __construct(private MemcacheClient $memcache) {}
    
  • Connection Pooling Configure multiple servers for failover and load balancing:

    druidvav_memcache:
        servers:
            primary:
                host: 'memcache-primary'
                port: 11211
                weight: 1
            secondary:
                host: 'memcache-secondary'
                port: 11211
                weight: 1
    

Gotchas and Tips

Pitfalls

  1. Connection Issues

    • Memcache servers may be unreachable. Handle exceptions gracefully:
      try {
          $value = $this->memcache->get($key);
      } catch (\MemcacheException $e) {
          // Fallback to database or return default
          return $this->fallbackLogic();
      }
      
  2. Data Serialization

    • Memcache stores data as strings. Complex objects must be serialized:
      $this->memcache->set('user', serialize($user), 3600);
      $user = unserialize($this->memcache->get('user'));
      
    • Tip: Use json_encode()/json_decode() for JSON-serializable objects.
  3. TTL Misconfiguration

    • Setting 0 for TTL disables expiration. Use false to let Memcache manage it:
      $this->memcache->set($key, $value, false); // No expiration
      
  4. Key Collisions

    • Memcache keys are case-sensitive and limited to 250 bytes. Use a consistent naming scheme:
      $key = 'app:user:' . $userId; // Prefix keys for namespacing
      
  5. Memory Limits

    • Memcache is memory-based. Monitor usage to avoid evictions:
      memcached-tool localhost:11211 stats
      

Debugging

  • Enable Logging Configure Monolog to log Memcache operations:

    # config/packages/monolog.yaml
    handlers:
        memcache:
            type: stream
            path: "%kernel.logs_dir%/memcache.log"
            level: debug
            channels: ["memcache"]
    
  • Check Server Status Use memcache->getStats() to diagnose issues:

    $stats = $this->memcache->getStats();
    if ($stats['uptime'] === 0) {
        throw new \RuntimeException('Memcache server is down');
    }
    

Extension Points

  1. Custom Serialization Override the default serializer via configuration:

    druidvav_memcache:
        serializer: App\Service\CustomMemcacheSerializer
    
  2. Event Listeners Subscribe to Memcache events (e.g., cache misses) using Symfony’s event dispatcher:

    $dispatcher->addListener(
        MemcacheEvents::MISS,
        [$this, 'onCacheMiss']
    );
    
  3. Fallback Strategies Implement a decorator pattern for fallback logic:

    class FallbackMemcacheClient implements MemcacheClientInterface
    {
        public function __construct(
            private MemcacheClient $memcache,
            private FallbackService $fallback
        ) {}
    
        public function get($key)
        {
            $value = $this->memcache->get($key);
            return $value !== false ? $value : $this->fallback->get($key);
        }
    }
    

Configuration Quirks

  • Default Server If no server is specified, the bundle uses default. Ensure this is defined.

  • Weight Parameter Higher weights increase the likelihood of selecting a server for operations (useful for load balancing).

  • Compression The bundle does not support compression by default. Use gzip at the Memcache server level if needed.

Performance Tips

  • Batch Operations Use add() instead of set() to avoid overwriting existing keys accidentally.
  • Multi-GET Fetch multiple keys in one call:
    $keys = ['key1', 'key2', 'key3'];
    $values = $this->memcache->getMulti($keys);
    
  • Avoid Large Values Memcache is not optimized for large objects. Offload large data to files or databases.
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle