6

With symfony 3.1 we got Cache Component (https://github.com/symfony/cache)

I can't find any documentation or examples for this component because it's new.

Can anybody write simple example how to use this component with symfony 3.1

gam6itko
  • 15,128
  • 2
  • 19
  • 18
Danil Pyatnitsev
  • 2,172
  • 2
  • 26
  • 39

1 Answers1

10

The cache component is mainly used internal in Symfony for Serializers etc.

But the latest FrameworkBundle already supports creating your own cache pools via config.yml. There doesnt seem to be any docs on this at the moment, so i digged myself through:

In config.yml you can create f.e. a new cache

framework:
...
    cache:
        default_redis_provider: redis://%cache.redis_host%:%cache.redis_port%/%cache:redis_db%
        pools:
           my_cache:
             adapter: cache.adapter.redis
             public: true
             default_lifetime: 1200
             provider: cache.default_redis_provider 

Of course you can also just make your own service defintion.

In your code you can then use the created cache pool to create CacheItems and cache them:

$cacheItem = $this->get('my_cache')->getItem($cacheKey = $item->getId());
if(!$cacheItem->isHit()){
   $cacheItem->set($item);
   $cacheItem->expiresAfter(null); //this needs to be called to use defaultTime
   $this->get('my_cache')->save($cacheItem);
}

The Psr-6 CacheItem gets created by the pool if it not exists in the cache.
It will get the key that it first got queried with. Then you can set a value and expiration time and save it to the cache.

For more infos on what and how you can do with the PSR-6 cache see here: http://www.php-fig.org/psr/psr-6/

The symfony docs for the component (note: only for the component, not for the framework integration) are still a PR but you can precheck it here: https://github.com/symfony/symfony-docs/pull/6515

ivoba
  • 5,780
  • 5
  • 48
  • 55
  • 2
    I've went through docs multiple times looking why my pool does not show up in the container of Symfony once declared. Turns out it **has to be marked `public` explicitly**, just like you show in your asnwer. Thanks! – SteveB Oct 13 '16 at 08:49