PHPackages                             webarchitect609/memcache-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. webarchitect609/memcache-bundle

ActiveSymfony-bundle[Caching](/categories/caching)

webarchitect609/memcache-bundle
===============================

Memcache Doctrine caching and session storage in the Web Debug Toolbar

v2.1.18(1y ago)0680↓100%1MITPHPPHP ^8.0

Since Apr 11Pushed 1y agoCompare

[ Source](https://github.com/webarchitect609/LswMemcacheBundle)[ Packagist](https://packagist.org/packages/webarchitect609/memcache-bundle)[ Docs](http://www.leaseweblabs.com)[ RSS](/packages/webarchitect609-memcache-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (3)Versions (49)Used By (0)

Fork description
================

[](#fork-description)

This fork was created for these reasons:

1. Allow passing environment variables in the bundle config.
2. Comply with PSR-4 autoloading standard.

It's **not maintained** and barely alive only for some legacy projects.

Deprecated
----------

[](#deprecated)

This repository is no longer being actively maintained. We encourage you to not use this code. If you rely on this code you might want to fork the repository to keep your systems from breaking, if we remove this repository in the future.

[![Build Status](https://camo.githubusercontent.com/7a79a7a7c80c20b6fb909867ce67e76c8787deaf241ac120d880c30698290188/68747470733a2f2f7472617669732d63692e6f72672f4c656173655765622f4c73774d656d636163686542756e646c652e737667)](https://travis-ci.org/LeaseWeb/LswMemcacheBundle)[![Average time to resolve an issue](https://camo.githubusercontent.com/3694db1a48c88308147950f386de30c23647749c79706c3af7230b6a9fc73297/687474703a2f2f697369746d61696e7461696e65642e636f6d2f62616467652f7265736f6c7574696f6e2f4c656173655765622f4c73774d656d636163686542756e646c652e737667)](http://isitmaintained.com/project/LeaseWeb/LswMemcacheBundle "Average time to resolve an issue")[![Percentage of issues still open](https://camo.githubusercontent.com/40a01c6d852dd42c13bdaa4e2e55b64f23b9b8ec77562e4da44a72a9078293ae/687474703a2f2f697369746d61696e7461696e65642e636f6d2f62616467652f6f70656e2f4c656173655765622f4c73774d656d636163686542756e646c652e737667)](http://isitmaintained.com/project/LeaseWeb/LswMemcacheBundle "Percentage of issues still open")[![Total Downloads](https://camo.githubusercontent.com/279659d4358ddfae10cf7dbb4ea23190756aaef7618a37ccea403abe2c527a4c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c656173657765622f6d656d63616368652d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/leaseweb/memcache-bundle)

LswMemcacheBundle
=================

[](#lswmemcachebundle)

[![screenshot](https://camo.githubusercontent.com/d5a1be1a22ec6b8c23eb8f85bb2ed56742ec640d6d1927045f4f19bbc51ebdd0/687474703a2f2f7777772e6c656173657765626c6162732e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031352f30362f6d656d63616368655f76322e706e67)](https://camo.githubusercontent.com/d5a1be1a22ec6b8c23eb8f85bb2ed56742ec640d6d1927045f4f19bbc51ebdd0/687474703a2f2f7777772e6c656173657765626c6162732e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031352f30362f6d656d63616368655f76322e706e67)

If you want to optimize your web application for high load and/or low load times Memcache is an indispensable tool. It will manage your session data without doing disk I/O on web or database servers. You can also run it as a central object storage for your website. In this role it is used for caching database queries using the Doctrine caching support or expensive API calls by implementing the caching using Memcache "get" and "set" commands.

This Symfony bundle will provide Memcache integration into Symfony and Doctrine for session storage and caching. It has full Web Debug Toolbar integration that allows you to analyze and debug the cache behavior and performance.

[Read the LeaseWebLabs blog about LswMemcacheBundle](http://www.leaseweblabs.com/2015/06/version-2-of-our-memcache-bundle-for-symfony-is-released/)

### Requirements

[](#requirements)

- PHP 5.3.10 or higher
- php-memcache 3.0.6 or higher
- memcached 1.4 or higher

NB: This bundle no longer uses the PHP "memcached" extension that uses "libmemcached", see "Considerations".

PHP7 support is currently (experimentally) available by compiling and installing:

### Installation

[](#installation)

To install LswMemcacheBundle with Composer just add the following to your 'composer.json' file:

```
{
    require: {
        "leaseweb/memcache-bundle": "*",
        ...
    }
}

```

The next thing you should do is install the bundle by executing the following command:

```
php composer.phar update leaseweb/memcache-bundle

```

Finally, add the bundle to the registerBundles function of the AppKernel class in the 'app/AppKernel.php' file:

```
public function registerBundles()
{
    $bundles = array(
        ...
        new Lsw\MemcacheBundle\LswMemcacheBundle(),
        ...
    );

```

Configure the bundle by adding the following to app/config/config.yml':

```
lsw_memcache:
    session:
        pool: default
    pools:
        default:
            servers:
              - { host: localhost, tcp_port: 11211 }
```

Install the following dependencies (in Debian based systems using 'apt'):

```
apt-get install memcached php5-memcache

```

Do not forget to restart you web server after adding the Memcache module. Now the Memcache information should show up with a little double arrow (fast-forward) icon in your debug toolbar.

### Usage

[](#usage)

When you want to use the cache from the controller you can simply call:

```
$this->get('memcache.default')->set('someKey', 'someValue', 0, $timeToLive);
$this->get('memcache.default')->get('someKey');

```

The above example shows how to store value 'someValue' under key 'someKey' for a maximum of $timeToLive seconds (the 0 parameter are the 'flags'). In the second line the value is retrieved from Memcache. If the key can not be found or the specified number of seconds have passed the 'get' function returns the value 'false'.

### Configuration

[](#configuration)

Below you can see an example configuration for this bundle.

```
lsw_memcache:
    pools:
        default:
            servers:
                - { host: 10.0.0.1, tcp_port: 11211, weight: 15 }
                - { host: 10.0.0.2, tcp_port: 11211, weight: 30 }
            options:
		        allow_failover: true
		        max_failover_attempts: 20
		        default_port: 11211
		        chunk_size: 32768
		        protocol: ascii
		        hash_strategy: consistent
		        hash_function: crc32
		        redundancy: true
		        session_redundancy: 2
		        compress_threshold: 20000
		        lock_timeout: 15
        sessions:
            servers:
                - { host: localhost, tcp_port: 11212 }
```

### Session Support

[](#session-support)

This bundle also provides support for storing session data on Memcache servers. To enable session support you will have to enable it through the `session` key (`auto_load` is true by default). Note that the only required subkey of the session support is `pool` (a valid pool). You can also specify a key `prefix`and a `ttl`.

```
lsw_memcache:
    session:
        pool: sessions
        auto_load: true
        prefix: "session_"
        ttl: 7200
        locking: true
        spin_lock_wait: 150000
    # pools
```

Note that the session locking is enabled by default and the default spin lock is set to poll every 150 milliseconds (150000 microseconds).

### Session Management for applications running behind a load balancer

[](#session-management-for-applications-running-behind-a-load-balancer)

When your application is running on multiple servers you have to be aware that all your instances should be comunicating with 1 Caching server for consistency; otherwise each instance would have its own session and this would produce unexpected results.

In order for you to avoid the problem described above you have to add LockingSessionHandler as service. By doing this, all your instances will use the session handler and the session handler would store the data in the configured memcache server.

```
my.memcache.service:
    class: Memcache
    calls:
        - [addServer, ['your_memcache_address', 'your_memcache_port']]

my.memcached.session.handler:
    class: Lsw\MemcacheBundle\Session\Storage\LockingSessionHandler
   arguments:
       - "@my.memcache.service"
       - prefix: 'your_prefix'
       - expiretime: 'your_expire_time'
```

### Doctrine Support

[](#doctrine-support)

This bundle also provides support for Doctrine caching on Memcache servers. To enable Doctrine caching you will have to enable it through the `doctrine` key. Note that you can specify all three kinds of Doctrine caching: 'metadata', 'result' and 'query'. The required keys within those subkeys are both `pool` (a valid pool) and `entity_manager` (normally: default). You can also specify a `prefix`.

```
lsw_memcache:
    doctrine:
        metadata_cache:
            pool: default
            entity_manager: default          # the name of your entity_manager connection
            document_manager: default        # the name of your document_manager connection
        result_cache:
            pool: default
            entity_manager: [default, read]  # you may specify multiple entity_managers
            prefix: "result_"                # you may specify a prefix for the entries
        query_cache:
            pool: default
            entity_manager: default
    # pools
```

### Firewall Support

[](#firewall-support)

This bundle also provides support a firewall that limits the number of concurrent requests per IP address. It maintains a counter of running requests per IP address and delays (throttles) the requests if nessecary. To enable firewall support you will have to enable it through the `firewall` key. Note that the only required subkey of the firewall support is `pool` (a valid pool). You can also specify a key `prefix`and a `concurrency` (default is 10). If you use one or more reverse proxies, then specify them in the `reverse_proxies` key.

```
lsw_memcache:
    firewall:
        pool: firewall
        prefix: "firewall_"
        concurrency: 10
        reverse_proxies: [10.0.0.1]
    # pools
```

### ADP: Anti Dog Pile

[](#adp-anti-dog-pile)

Let us examine a high traffic website case and see how Memcache behaves:

Your cache is stored for 90 minutes. It takes about 3 second to calculate the cache value and 1 ms second to read the cached value from the cache. You have about 5000 requests per second and let's assume that the value is cached. You get 5000 requests per second taking about 5000 ms to read the values from cache. You might think that that is not possible since 5000 &gt; 1000, but that depends on the number of worker processes on your web server. Let's say it is about 100 workers (under high load) with 75 threads each. Your web requests take about 20 ms each. Whenever the cache invalidates (after 90 minutes), during 3 seconds, there will be 15000 requests getting a cache miss. All the threads getting a miss will start to calculate the cache value (because they don't know the other threads are doing the same). This means that during (almost) 3 seconds the server wont answer a single request, but the requests keep coming in. Since each worker has 75 threads (holding 100 x 75 connections), the amount of workers has to go up to be able to process them.

The heavy forking will cause extra CPU usage and the each worker will use extra RAM. This unexpected increase in RAM and CPU is called the 'dog pile' effect or 'stampeding herd' or 'thundering herd' and is very unwelcome during peak hours on a web service.

There is a solution: we serve the old cache entries while calculating the new value and by using an atomic read and write operation we can make sure only one thread will receive a cache miss when the content is invalidated. The algorithm is implemented in AntiDogPileMemcache class in LswMemcacheBundle. It provides the getAdp(), setAdp() and deleteAdp() functions that can be used as replacements for the normal get, set and delete.

Please note:

- ADP might not be needed if you have low amount of hits or when calculating the new value goes relatively fast.
- ADP might not be needed if you can break up the big calculation into smaller, maybe even with different timeouts for each part.
- ADP might get you older data than the invalidation that is specified. Especially when a thread/worker gets "false" for "get" request, but fails to "set" the new calculated value afterwards.
- ADP's "getAdp", "setAdp" and "deleteAdp" are more expensive than the normal "get", "set" and "delete", slowing down all cache hits.
- ADP does not guarantee that the dog pile will not occur. Restarting Memcache, flushing data or not enough RAM will also get keys evicted and you will run into the problem anyway.

### Considerations

[](#considerations)

LswMemcacheBundle uses the 'memcache' PHP extension (memcached client) and not the libmemcache based 'memcached' PHP extension.

Major version 1 of this bundle used the other extension. In major version 2 of this bundle the full featured version 3.0.8 of PECL "memcache" (without the 'd') was chosen, due to it's complete feature set and good design and support.

### Known issues

[](#known-issues)

The session write that invokes a memcache set operation is executed after the page has been rendered. The collect call of the memcache data collector is executed before the rendering of the page is complete and therefor also before the session write is executed. This causes the session writes not to show up in the Web Debug Toolbar.

### Credits

[](#credits)

Doctrine support is based on the implementation in SncRedisBundle:

 by Henrik Westphal

- DependencyInjection/LswMemcacheExtension.php
- DependencyInjection/Configuration.php
- DependencyInjection/Compiler/EnableSessionSupport.php

Are based on implementation in:

 by Christian Soronellas

- Command/StatisticsCommand.php

Is based on an implementation in:

 by Kevin Boyd

### License

[](#license)

This bundle is under the MIT license.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 51.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~89 days

Recently: every ~299 days

Total

47

Last Release

680d ago

Major Versions

v1.2.18 → v2.0.02015-06-30

PHP version history (2 changes)v1.0.0PHP &gt;=5.3.2

v2.1.18PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/9f9a6e3ee8c76415a66949c630cd1281bfb6a232a5648b2410574fb6e1e09b65?d=identicon)[webarchitect609](/maintainers/webarchitect609)

---

Top Contributors

[![mevdschee](https://avatars.githubusercontent.com/u/1288217?v=4)](https://github.com/mevdschee "mevdschee (43 commits)")[![jasperstafleu](https://avatars.githubusercontent.com/u/2337759?v=4)](https://github.com/jasperstafleu "jasperstafleu (9 commits)")[![webarchitect609](https://avatars.githubusercontent.com/u/11293610?v=4)](https://github.com/webarchitect609 "webarchitect609 (8 commits)")[![h4cc](https://avatars.githubusercontent.com/u/2981491?v=4)](https://github.com/h4cc "h4cc (5 commits)")[![falvarez](https://avatars.githubusercontent.com/u/717175?v=4)](https://github.com/falvarez "falvarez (2 commits)")[![nrocco](https://avatars.githubusercontent.com/u/694012?v=4)](https://github.com/nrocco "nrocco (2 commits)")[![jimaek](https://avatars.githubusercontent.com/u/1834071?v=4)](https://github.com/jimaek "jimaek (2 commits)")[![dbu](https://avatars.githubusercontent.com/u/76576?v=4)](https://github.com/dbu "dbu (2 commits)")[![lancergr](https://avatars.githubusercontent.com/u/1558756?v=4)](https://github.com/lancergr "lancergr (1 commits)")[![mauriau](https://avatars.githubusercontent.com/u/522635?v=4)](https://github.com/mauriau "mauriau (1 commits)")[![d3f3kt](https://avatars.githubusercontent.com/u/5670972?v=4)](https://github.com/d3f3kt "d3f3kt (1 commits)")[![onewheelskyward](https://avatars.githubusercontent.com/u/314750?v=4)](https://github.com/onewheelskyward "onewheelskyward (1 commits)")[![spoelwijk](https://avatars.githubusercontent.com/u/81775?v=4)](https://github.com/spoelwijk "spoelwijk (1 commits)")[![dhanielo](https://avatars.githubusercontent.com/u/1815478?v=4)](https://github.com/dhanielo "dhanielo (1 commits)")[![Arthurhall](https://avatars.githubusercontent.com/u/4819392?v=4)](https://github.com/Arthurhall "Arthurhall (1 commits)")[![GabrielAnca](https://avatars.githubusercontent.com/u/251391?v=4)](https://github.com/GabrielAnca "GabrielAnca (1 commits)")[![gfyrag](https://avatars.githubusercontent.com/u/9094799?v=4)](https://github.com/gfyrag "gfyrag (1 commits)")[![gmansilla](https://avatars.githubusercontent.com/u/477676?v=4)](https://github.com/gmansilla "gmansilla (1 commits)")[![jbaginski](https://avatars.githubusercontent.com/u/201855?v=4)](https://github.com/jbaginski "jbaginski (1 commits)")

---

Tags

cachememcachedsessionmemcache

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/webarchitect609-memcache-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/webarchitect609-memcache-bundle/health.svg)](https://phpackages.com/packages/webarchitect609-memcache-bundle)
```

###  Alternatives

[sabre/cache

Simple cache abstraction layer implementing PSR-16

541.2M3](/packages/sabre-cache)[apix/cache

A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache taggging and indexing to Redis, Memcached, PDO/SQL, APC and other adapters.

114542.8k6](/packages/apix-cache)[robinn/phpcacheadmin

A web dashboard for your favorite caching system.

4441.1k1](/packages/robinn-phpcacheadmin)[alekseykorzun/memcached-wrapper-php

Optimized PHP 5 wrapper for Memcached extension that supports dog-piling, igbinary and local storage

2984.6k1](/packages/alekseykorzun-memcached-wrapper-php)[beryllium/cachebundle

Provides an interface to Memcache for Symfony2 applications

32135.8k](/packages/beryllium-cachebundle)[ihor/cachalot

Cache a lot in a proper way (APC, XCache, Memcached, Redis, Couchbase)

2528.1k](/packages/ihor-cachalot)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
