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

leaseweb/memcache-bundle

Deprecated Symfony bundle adding Memcache (php-memcache) integration for sessions and caching, including Doctrine support and Web Debug Toolbar profiling to analyze cache behavior and performance under high load. Not actively maintained; consider forking.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require leaseweb/memcache-bundle

Add to AppKernel.php:

new Lsw\MemcacheBundle\LswMemcacheBundle(),
  1. Basic Configuration (config.yml):

    lsw_memcache:
        pools:
            default:
                servers:
                    - { host: localhost, tcp_port: 11211 }
    
  2. First Use Case: Inject the Memcache client in a controller/service:

    use Lsw\MemcacheBundle\Client\MemcacheClientInterface;
    
    public function __construct(MemcacheClientInterface $memcache)
    {
        $this->memcache = $memcache;
    }
    
    public function cacheExample()
    {
        $this->memcache->set('key', 'value', 0, 3600); // 1 hour TTL
        $value = $this->memcache->get('key');
    }
    

Key Starting Points

  • Debug Toolbar: Memcache stats appear under the "Memcache" tab in Symfony Profiler.
  • Session Storage: Enable via session.pool in config (see Session Support).
  • Doctrine Caching: Configure doctrine.metadata_cache, doctrine.result_cache, or doctrine.query_cache.

Implementation Patterns

1. Memcache Client Usage

Basic CRUD Operations

// Set with TTL (0 = no expiration)
$this->memcache->set('user:123:profile', $profileData, 0, 3600);

// Get with fallback
$profileData = $this->memcache->get('user:123:profile') ?: $this->loadFromDb();

// Delete
$this->memcache->delete('user:123:profile');

// Increment/Decrement (e.g., for counters)
$this->memcache->increment('hit_counter', 1);

Anti-Dog-Pile (ADP) Pattern

// Atomic read-modify-write to prevent stampedes
$oldValue = $this->memcache->getAdp('expensive:calc:123');
if ($oldValue === false) {
    $newValue = $this->expensiveCalculation();
    $this->memcache->setAdp('expensive:calc:123', $newValue, 0, 3600);
} else {
    // Use stale data if available
}

2. Session Management

Load Balancer Compatibility

# config.yml
lsw_memcache:
    session:
        pool: sessions
        locking: true  # Critical for multi-server setups
        spin_lock_wait: 150000  # 150ms lock retry interval

Custom Session Handler (Advanced)

# services.yml
my.session.handler:
    class: Lsw\MemcacheBundle\Session\Storage\LockingSessionHandler
    arguments:
        - "@memcache.sessions"  # Your configured pool service
        - { prefix: "app_sess_", expiretime: 7200 }

3. Doctrine Caching

Configure Caching Layers

# config.yml
lsw_memcache:
    doctrine:
        metadata_cache:
            pool: default
            entity_manager: default
        result_cache:
            pool: default
            entity_manager: [default, read_replica]
            prefix: "result:"
        query_cache:
            pool: default
            entity_manager: default

Query-Specific Caching

// Enable result caching for a query
$query->useResultCache(true);
$query->setCacheLifetime(300); // 5 minutes

4. Firewall/Throttling

# config.yml
lsw_memcache:
    firewall:
        pool: firewall
        concurrency: 50  # Max 50 concurrent requests per IP
        reverse_proxies: [10.0.0.1, 10.0.0.2]  # Trusted proxies

Check Throttle Status

$this->get('lsw_memcache.firewall')->isAllowed($request->getClientIp());

5. Multi-Pool Strategies

# config.yml
lsw_memcache:
    pools:
        primary:
            servers: [{ host: memcache1, port: 11211 }]
        secondary:
            servers: [{ host: memcache2, port: 11211 }]
            options:
                redundancy: true
                session_redundancy: 2

Dynamic Pool Selection

$pool = $this->get('memcache.primary'); // Inject via DI
if ($pool->isDown()) {
    $pool = $this->get('memcache.secondary');
}

Gotchas and Tips

1. Common Pitfalls

Issue Solution
Session data missing in Profiler Sessions are written after page render; use session_write_close() early.
Connection failures Enable allow_failover: true and monitor max_failover_attempts.
Stale ADP data ADP may return old values during race conditions; design for eventual consistency.
Memory bloat Set compress_threshold (e.g., 20000) to compress large values.
PHP 7+ compatibility Use pecl-memcache for PHP 7.

2. Debugging Tips

  • Profiler Tab: Inspect Memcache tab for hit/miss ratios, latency, and memory usage.
  • CLI Stats:
    php app/console lsw:memcache:stats
    
  • Log Failures:
    # config.yml
    lsw_memcache:
        pools:
            default:
                options:
                    log_errors: true
    

3. Performance Tuning

Parameter Recommendation
chunk_size Increase (e.g., 65536) for large objects.
hash_strategy Use consistent for multi-server setups.
session_redundancy Set to 2 for high-availability sessions.
lock_timeout Reduce (e.g., 5) for faster session locks in high-concurrency apps.

4. Extension Points

Custom Memcache Client

// services.yml
my.custom.memcache:
    class: MyApp\CustomMemcacheClient
    arguments:
        - "@memcache.default"
    tags:
        - { name: lsw_memcache.client, alias: custom }

Event Listeners

// Subscribe to cache events
use Lsw\MemcacheBundle\Event\MemcacheEvents;

public function onCacheMiss(MemcacheMissEvent $event) {
    if ($event->getKey() === 'expensive:calc') {
        $event->setValue($this->fallbackCalculation());
    }
}

5. Migration Notes

  • From memcached extension: This bundle requires the memcache extension (not memcached).
  • Symfony 4+: Use config/packages/lsw_memcache.yaml instead of config.yml.
  • Doctrine 2.7+: Ensure entity_manager names match your Doctrine config.

6. Anti-Patterns to Avoid

  • Ignoring TTLs: Always set ttl (even if 0 for "no expiration").
  • Blocking Calls: Avoid long-running get()/set() in request paths.
  • Overusing ADP: ADP adds overhead; reserve for truly expensive operations.
  • Hardcoded Keys: Use namespacing (e.g., user:123:profile) to avoid collisions.

7. Legacy Quirks

  • YAML Deprecation: Symfony 3.2+ may warn about YAML config; use !tagged for complex structures.
  • Windows Support: Tested in v2.0+, but some features (e.g., session locking) may behave differently.
  • PHP 5.3: Avoid if possible; upgrade to PHP 7+ for better performance.

8. When to Fork

  • Critical Bugs: If the bundle breaks due to unmaintained dependencies (e.g., Symfony 5+).
  • Feature Gaps: Add missing features (e.g., Memcached SASL auth) and submit PRs upstream.
  • Security Patches: Backport fixes if the original repo is abandoned.

9. Alternatives

Use Case Alternative Bundle
Redis Support snc/redis-bundle
Modern Memcached predis/predis (with `php-m
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat