Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use TagAwareAdapter per config.yml in Symfony 3.2?

Tags:

php

symfony

I am aware that I can define a cache in Symfony 3.2 like that in my config.yml:

    cache:
    default_redis_provider: redis://%redis_password%@%redis_host%:%redis_port%
    pools:
        my_redis_cache:
            adapter: cache.adapter.redis
            public: true
            default_lifetime: 1200
            provider: cache.default_redis_provider

E.g. in my Controller I can simple use

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

Now since Symfony 3.2 we have a fantastic new feature called TagAwareAdapter - which allows cache invalidation by tags.

This is done in code by:

$cache = new TagAwareAdapter(
// Adapter for cached items
new FilesystemAdapter(),
// Adapter for tags
new RedisAdapter('redis://localhost')
);

But could I define it in my config.yml?

I am looking for something like:

    cache:
    default_redis_provider: redis://%redis_password%@%redis_host%:%redis_port%
    pools:
        my_redis_cache:
            adapter: cache.adapter.redis
            public: true
            default_lifetime: 1200
            provider: cache.default_redis_provider
        my_tag_aware_cache:
            adapter: cache.adapter.tagawareadapter
            provider:
                - my_file_cache
                - my_redis_cache

But I have no idea how to define it - I am playing try & error since a while now - all I got was error so far.

like image 387
LBA Avatar asked Oct 23 '25 15:10

LBA


2 Answers

The upper answer provides the solution and its a good one, I'll just put it all together as an answer, as I also wasted some time finding out how to use the TagAwareAdapter. This is my solution for Symfony 3.4.

config.yml

cache:
    pools:
        app.cache.file:
            public: true
            adapter: cache.adapter.filesystem
        app.cache.redis:
            public: true
            adapter: cache.adapter.redis

services.yml:

myapp.cache:
    public: true
    class: Symfony\Component\Cache\Adapter\TagAwareAdapter
    arguments: [ '@app.cache.file', '@app.cache.redis' ]

The use it like this(eg in Controller):

/** @var TagAwareAdapterInterface $cache */
$cache = $this->get('myapp.cache');

Don't forget to have a redis instance in place and install redis package:

composer require predis/predis
like image 90
klodoma Avatar answered Oct 25 '25 04:10

klodoma


Stupid me. I could do it by defining a simple service in services.yml:

    my_tag_aware_cache:
        class: Symfony\Component\Cache\Adapter\TagAwareAdapter
        arguments: [ '@my_file_cache', '@my_redis_cache' ]

Now I receive my cache in controller with

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

and it's a TagAware Cache.

Or is there another/better way to achieve this?

like image 32
LBA Avatar answered Oct 25 '25 05:10

LBA