I’ve the following to cache model query and it is working fine,
public static function getSubcategories($partnerId)
{
$instance = new self();
$q = $instance->modelsManager->createBuilder();
$q = $q->columns([
'cc.category',
'cc.type',
'cc.slug',
'cc.title',
])
->from(['cc' => CatalogCategories::class])
->join(PartnerTypes::class, 'cc.category = pt.typeSlug', 'pt')
->where('pt.parentId = :partnerId:', compact('partnerId'));
$cacheKey = 'getSubcategories';
if ($partnerId) {
$cacheKey .= '_' . $partnerId;
}
$q = $q->getQuery();
if($instance->getDI()->get('config')->cache->isEnabled){
$q = $q->cache(
[
'key' => $cacheKey,
'lifetime' => $instance->getDI()->get('config')->cache->duration->min15,
]
);
}
return $q->execute();
}
But how to invalidate cache with a key, i’ve read the documentation but couldn’t find anything how to invalidate the cache with a key.
3
Answers
If you are looking to do just an occasional invalidation, I tend to use a simple cache-buster.
When my CI/CD pipelines run, I will generate a file that looks like
<?php return ['cache' => ['buster' => 'abc123']];
whereabc123
is the commit hash.Then, in the code, I use the cache-buster as part of any given key (more commonly the prefix) that I want to invalidate on deployment.
It’s worth noting that you aren’t literally invalidating the cache here, but instead changing the prefix for the cache, which in effect invalidates it. That is to say that if you had an infinite TTL on your cache’s, they would never expire. You want your TTL to be reasonable so they invalidate after a reasonable amount of time so you’re cache server isn’t holding onto dead data.
You can use the
delete()
method of the cache service/adapter that you are using, i.e.As a side comment, if you add the type of $partnerId, you can exit the function earlier and remove the extra condition that will always validate to true:
Phalcon 4 provides a method to do the same.
to delete an item from the cache you need to call the delete() method with a key. The method returns true on success and false on failure. `
Reference: Docs
Hope it helps