<?php
namespace GlobusSW6\Service\Cache;
use Shopware\Core\Framework\Adapter\Cache\RedisConnectionFactory;
use Shopware\Storefront\Framework\Cache\Event\HttpCacheHitEvent;
use Shopware\Storefront\Framework\Cache\Event\HttpCacheItemWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* @see https://speakerdeck.com/beberlei/best-practices-for-running-shopware-6-in-production?slide=14
*/
class HttpCacheHitMissRater implements EventSubscriberInterface
{
private RedisConnectionFactory $redisConnectionFactory;
private string $redisDsn;
private $redis;
/**
* @param RedisConnectionFactory $redisConnectionFactory
* @param string $redisDsn
*/
public function __construct(RedisConnectionFactory $redisConnectionFactory, string $redisDsn)
{
$this->redisConnectionFactory = $redisConnectionFactory;
$this->redisDsn = $redisDsn;
}
public static function getSubscribedEvents()
{
return [
HttpCacheItemWrittenEvent::class => 'onCacheMiss',
HttpCacheHitEvent::class => 'onCacheHit',
];
}
public function onCacheMiss(HttpCacheItemWrittenEvent $event)
{
try {
$this->getRedis()->hIncrBy('http_cache_misses', date('YmdH'), 1);
} catch (\Throwable $t) {
// nth
}
}
public function onCacheHit(HttpCacheHitEvent $event)
{
try {
$this->getRedis()->hIncrBy('http_cache_hits', date('YmdH'), 1);
} catch (\Throwable $t) {
// nth
}
}
private function getRedis()
{
if ($this->redis === null) {
$this->redis = $this->redisConnectionFactory->create($this->redisDsn);
}
return $this->redis;
}
}