8000 [Cache] Count cache hits/misses in ProxyAdapter · symfony/symfony@2cbd27f · GitHub
[go: up one dir, main page]

Skip to content

Commit 2cbd27f

Browse files
[Cache] Count cache hits/misses in ProxyAdapter
1 parent 38c36c2 commit 2cbd27f

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

src/Symfony/Component/Cache/Adapter/ProxyAdapter.php

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ class ProxyAdapter implements CacheItemPoolInterface
2222
{
2323
private $pool;
2424
private $createCacheItem;
25+
private $hits = 0;
26+
private $misses = 0;
2527

2628
public function __construct(CacheItemPoolInterface $pool)
2729
{
@@ -47,8 +49,13 @@ public function getItem($key)
4749
{
4850
$f = $this->createCacheItem;
4951
$item = $this->pool->getItem($key);
52+
if ($isHit = $item->isHit()) {
53+
++$this->hits;
54+
} else {
55+
++$this->misses;
56+
}
5057

51-
return $f($key, $item->get(), $item->isHit());
58+
return $f($key, $item->get(), $isHit);
5259
}
5360

5461
/**
@@ -120,6 +127,7 @@ private function doSave(CacheItemInterface $item, $method)
120127
if (!$item instanceof CacheItem) {
121128
return false;
122129
}
130+
123131
$item = (array) $item;
124132
$expiry = $item[CacheItem::CAST_PREFIX.'expiry'];
125133
$poolItem = $this->pool->getItem($item[CacheItem::CAST_PREFIX.'key']);
@@ -134,7 +142,33 @@ private function generateItems($items)
134142
$f = $this->createCacheItem;
135143

136144
foreach ($items as $key => $item) {
137-
yield $key => $f($key, $item->get(), $item->isHit());
145+
if ($isHit = $item->isHit()) {
146+
++$this->hits;
147+
} else {
148+
++$this->misses;
149+
}
150+
151+
yield $key => $f($key, $item->get(), $isHit);
138152
}
139153
}
154+
155+
/**
156+
* Returns the number of cache read hits.
157+
*
158+
* @return int
159+
*/
160+
public function getHits()
161+
{
162+
return $this->hits;
163+
}
164+
165+
/**
166+
* Returns the number of cache read misses.
167+
*
168+
* @return int
169+
*/
170+
public function getMisses()
171+
{
172+
return $this->misses;
173+
}
140174
}

src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,21 @@ public function createCachePool()
2929
{
3030
return new ProxyAdapter(new ArrayAdapter());
3131
}
32+
33+
public function testGetHitsMisses()
34+
{
35+
$pool = $this->createCachePool();
36+
37+
$this->assertSame(0, $pool->getHits());
38+
$this->assertSame(0, $pool->getMisses());
39+
40+
$bar = $pool->getItem('bar');
41+
$this->assertSame(0, $pool->getHits());
42+
$this->assertSame(1, $pool->getMisses());
43+
44+
$pool->save($bar->set('baz'));
45+
$bar = $pool->getItem('bar');
46+
$this->assertSame(1, $pool->getHits());
47+
$this->assertSame(1, $pool->getMisses());
48+
}
3249
}

0 commit comments

Comments
 (0)
0