How to clear ONLY stale cache in symfony?

32 Views Asked by At

Running Symfony 7.0, I am using Symfony's Cache, specifically the Doctrine DBAL Cache Adapter

To use a specific example:

use Symfony\Contracts\Cache\ItemInterface;

// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (ItemInterface $item): string {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

The cache item will be persisted forever in DB. When it expires, it will result in cache miss, but thats it, it will be updated but it will never be removed from DB.

I am looking for some command, that when I run it, it will clear ONLY ALL expired cache items.

Given that I know the structure of the specific table used internally for Doctrine cache, I could write a CRON that will just DELETE all rows using a timestamp, but is there some generic command which can be used (similar to symfony cache:clear)?

I need to do this, as I plan to cache a LOT of items using lot of unique keys, but the cache will be used frequently for limited time since creation, and then no more. With current cache implementation, the cache table will grow indefinitely.

1

There are 1 best solutions below

0
michnovka On

So after looking more througn Symfony doc's and source code, I found what I need is called Cache Pruning.

The DoctrineDbalAdapter implements PruneableInterface so I can just make a cron that calls the prune() method.

The command to call from symfony console is:

php bin/console cache:pool:prune