Skip to content

Instantly share code, notes, and snippets.

@BackEndTea
Created August 28, 2025 13:01
Show Gist options
  • Select an option

  • Save BackEndTea/ea3fbec02ae58fca191f2ff7c7404378 to your computer and use it in GitHub Desktop.

Select an option

Save BackEndTea/ea3fbec02ae58fca191f2ff7c7404378 to your computer and use it in GitHub Desktop.
<?php
use Psr\SimpleCache\CacheInterface;
interface Api {
public function get(array $data): mixed;
}
class CachedApi implements Api
{
public function __construct(
private Api $inner,
private CacheInterface $cache
){}
public function get(array $data): mixed
{
$key = $this->calculateKey($data);
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
$result = $this->inner->get($data);
$this->cache->set($key, $result, 3600);
return $result;
}
private function calculateKey(array $data): string {return ''; /* Implement a key calculation based on $data */ }
}
class CachedApiTest extends \PHPUnit\Framework\TestCase
{
public function testCacheOnlyFetchesOnce()
{
// In memory implementation of CacheInterface
$cache = new ArrayCache();
$inner = $this->createMock(Api::class);
$inner->expects($this->once())->method('get')->willReturn(['result']);
$cachedApi = new CachedApi($cache, $inner);
$this->assertEquals(['result'], $cachedApi->get(['param' => 'value']));
$this->assertEquals(['result'], $cachedApi->get(['param' => 'value']));
$this->assertEquals(['result'], $cachedApi->get(['param' => 'value']));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment