Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache in Symfony 2?

I need to cache some application specific data using Symfony 2's caching system so that I can run cache:clear to clear it. All the cache relies under app/cache but how do I actually go about caching data?

http://symfony.com/doc/current/cookbook/index.html

The only topic I see is about HTML caching with Varnish.

like image 472
Tower Avatar asked Jan 17 '12 10:01

Tower


People also ask

How to cache clear in Symfony?

Clearing the Cache To clear the cache you can use the bin/console cache:pool:clear [pool] command. That will remove all the entries from your storage and you will have to recalculate all the values. You can also group your pools into "cache clearers".


2 Answers

If you are using Doctrine already just use those cache classes.

Add a service to config.yml:

services:     cache:         class: Doctrine\Common\Cache\ApcCache 

And use it in your controller:

if ($fooString = $this->get('cache')->fetch('foo')) {     $foo = unserialize($fooString); } else {     // do the work     $this->get('cache')->save('foo', serialize($foo)); } 
like image 133
Kris Wallsmith Avatar answered Sep 23 '22 06:09

Kris Wallsmith


Simple way use Doctrine cache providers. At first, register service(sample in config.yml):

services:     memcached:         class: Memcached         calls:             - [ addServer, ['localhost', 11211] ]     memcached_cache:         class: Doctrine\Common\Cache\MemcachedCache         calls:             - [ setMemcached, [@memcached] ] 

Then to use get service, for example in controler:

$cache = $this->get('memcached_cache'); 

to send in another service use calls:

calls:     - [ setCacheProvider, [@memcached_cache] ] 

or arguments:

arguments:     - @memcached_cache 

In the same way, you can use other interfaces of Doctrine Cache package. Doctrine Cache provides a very simple interface for which several out of the box implementations are provided:

  • ApcCache (requires ext/apc)
  • ArrayCache (in memory, lifetime of the request)
  • FilesystemCache (not optimal for high concurrency)
  • MemcacheCache (requires ext/memcache)
  • MemcachedCache (requires ext/memcached)
  • PhpFileCache (not optimal for high concurrency)
  • RedisCache.php (requires ext/phpredis)
  • WinCacheCache.php (requires ext/wincache)
  • XcacheCache.php (requires ext/xcache)
  • ZendDataCache.php (requires Zend Server Platform)

If you do not already use Doctrine, you may require Common Library for Doctrine projects: php composer.phar require doctrine/common or require only Caching library offering an object-oriented API for many cache backends: php composer.phar require doctrine/cache

How to use Doctrine Caching you can read in Doctrine Common documentation on Doctrine Project web site

like image 32
Максим Шатов Avatar answered Sep 24 '22 06:09

Максим Шатов