Contributed by
Rob Frawley
and Nicolas Grekas
in #20858 and#21108.
The Symfony Cache component includes several adapters to support different caching mechanisms such as Redis, APCu, the filesystem, etc. In Symfony 3.3, we added a new adapter for Memcached.
When using it as a component, create first the connection to the Memcached server and then instantiate the new adapter:
1 2 3 4 | useSymfony\Component\Cache\Adapter\MemcachedAdapter;$client=MemcachedAdapter::createConnection('memcached://localhost');$cache=newMemcachedAdapter(\Memcached$client,$namespace='',$defaultLifetime=0); |
In addition to simple servers, the connection can also be a cluster of Memcached instances with all kinds of custom configuration:
1 2 3 4 5 6 7 8 9 | $client=MemcachedAdapter::createConnection(array(// format => memcached://[user:pass@][ip|host|socket[:port]][?weight=int]// 'weight' ranges from 0 to 100 and it's used to prioritize servers'memcached://my.server.com:11211''memcached://rmf:abcdef@localhost''memcached://127.0.0.1?weight=50''memcached://username:the-password@/var/run/memcached.sock''memcached:///var/run/memcached.sock?weight=20')); |
When used in a Symfony application, it's even simpler to configure and use Memcached:
1 2 3 4 5 6 7 8 9 10 11 | # app/config/config_prod.ymlframework:cache:# defaults to memcached://localhostdefault_memcached_provider:"memcached://my.server.com:11211"# ...pools:app.cache.products:adapter:cache.adapter.memcachedpublic:true# ... |
Now you can start storing and fetching items in your Memcached-based cache:
1 2 3 4 5 6 7 8 | $cacheProduct=$this->get('app.cache.products')->getItem($productId);if(!$cacheProduct->isHit()){$product=...$cacheProduct->set($product);$this->get('app.cache.products')->save($cacheProduct);}else{$product=$cacheProduct->get();} |