Skip to content

Commit

Permalink
feature #17734 [Cache] Count cache hits/misses in ProxyAdapter (nicol…
Browse files Browse the repository at this point in the history
…as-grekas)

This PR was merged into the 3.1-dev branch.

Discussion
----------

[Cache] Count cache hits/misses in ProxyAdapter

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #17537 partially
| License       | MIT
| Doc PR        | -

I propose to add this subset of the `Doctrine\Common\Cache\Cache` interface so that we can build data collectors on top and show these stats in the web profiler.
ping @javiereguiluz

Commits
-------

e6f21f9 [Cache] Count cache hits/misses in ProxyAdapter
  • Loading branch information
fabpot committed Mar 4, 2016
2 parents 1330662 + e6f21f9 commit b868feb
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/Symfony/Component/Cache/Adapter/ProxyAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ class ProxyAdapter implements CacheItemPoolInterface
{
private $pool;
private $createCacheItem;
private $hits = 0;
private $misses = 0;

public function __construct(CacheItemPoolInterface $pool)
{
Expand All @@ -47,8 +49,13 @@ public function getItem($key)
{
$f = $this->createCacheItem;
$item = $this->pool->getItem($key);
if ($isHit = $item->isHit()) {
++$this->hits;
} else {
++$this->misses;
}

return $f($key, $item->get(), $item->isHit());
return $f($key, $item->get(), $isHit);
}

/**
Expand Down Expand Up @@ -134,7 +141,33 @@ private function generateItems($items)
$f = $this->createCacheItem;

foreach ($items as $key => $item) {
yield $key => $f($key, $item->get(), $item->isHit());
if ($isHit = $item->isHit()) {
++$this->hits;
} else {
++$this->misses;
}

yield $key => $f($key, $item->get(), $isHit);
}
}

/**
* Returns the number of cache read hits.
*
* @return int
*/
public function getHits()
{
return $this->hits;
}

/**
* Returns the number of cache read misses.
*
* @return int
*/
public function getMisses()
{
return $this->misses;
}
}
17 changes: 17 additions & 0 deletions src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,21 @@ public function createCachePool()
{
return new ProxyAdapter(new ArrayAdapter());
}

public function testGetHitsMisses()
{
$pool = $this->createCachePool();

$this->assertSame(0, $pool->getHits());
$this->assertSame(0, $pool->getMisses());

$bar = $pool->getItem('bar');
$this->assertSame(0, $pool->getHits());
$this->assertSame(1, $pool->getMisses());

$pool->save($bar->set('baz'));
$bar = $pool->getItem('bar');
$this->assertSame(1, $pool->getHits());
$this->assertSame(1, $pool->getMisses());
}
}

0 comments on commit b868feb

Please sign in to comment.