Created
August 28, 2025 13:01
-
-
Save BackEndTea/ea3fbec02ae58fca191f2ff7c7404378 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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