How does Cache Invalidation of symfony 3 work?

Viewed 868

Hello I want to integrate the invalidation of cache of symfony but this one does not delete the cache I use memcached

In the repository I add the tags

$query = $this->getEntityManager()->createQuery($sql)->setParameters($params);
 
$cacheData = $cache->getItem(md5(serialize($query->getParameters())).$page);
 
 
if (!$cacheData->isHit()) {
$result = $query->setFirstResult(($page-1) * $maxPerPage)->setMaxResults($maxPerPage)
->useResultCache(true, 3000, md5(serialize($query->getParameters())).$page )
->useQueryCache(true)
->getResult();
 
$cacheData->set($result);
 
$cache->save($cacheData);
$cacheData->tag(['media', 'media_' . $category]);
} else {
$result = $cacheData->get();
}

When I add a data I empty the cache as if below but it does not empty

$cache = new TagAwareAdapter($this->get('cache.app'));
$cache->invalidateTags(['media']);
2 Answers

In Symfony 3.4 I am currently using cache tag invalidation like so:

Cache service declaration

framework:
    #...
    cache:
        prefix_seed: '%kernel.environment%'
        pools:
            cache.pool.permissions:
                adapter: cache.adapter.apcu

#...
services:
    cache.permissions:
        class: Symfony\Component\Cache\Adapter\TagAwareAdapter
        public: true
        arguments:
            - '@cache.pool.permissions'

Controller

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{

    public function cacheAction()
    {
        $cache = $this->get('cache.permissions');
        $cacheItem = $cache->getItem('user-test');
        $cache->save($cacheItem->set('HI')->tag(['permissions', 'permissions-user', 'permissions-user-test']));

        dump($cacheItem->get()); //"HI"

        dump($cache->invalidateTags(['permissions-user-test'])); //true

        dump($cacheItem->get()); //"HI" - this is desired

        $cacheItem = $cache->getItem('user-test'); //get current cache item reference

        dump($cacheItem->isHit()); //false

        dump($cacheItem->get()); //null
     }
}

To expand; invalidating a cache tag does NOT delete the cache item from the caching service. It only increments the cache item version number, this causes additional references to the cache item to be a miss. This is the intended functionality to avoid race conditions. [sic]

To remove it from the cache entirely you MUST use $cache->deleteItem('user-test');

NOTE: There is a bug in Symfony 3.4.9 that tag invalidation is not persisted. Please update to Symfony 3.4.10 to resolve the issue.

Related