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.
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".
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)); }
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With