Another caching article you think and feel . And who writes PHP these days. But wait, it's not only about caching and PHP, these are only used as examples here.
When writing on another topic a need arose to point out one extra thing in writing a clean and good code: don't invite the wheel.
Consider example
class Foo
{
private $cache = [];
private $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
public function getBar(string $someValue): mixed
{
if (!key_exists($someValue, $this->cache)) {
$this->cache[$someValue]=
$this->bar->getBySomeValue($someValue);
}
return $this->cache[$someValue];
}
}
It seems very easy to code and test. So let's write it. But what about cache invalidation and memory usage?
So let's add them... by using library. For PHP is Monolog the standard, so
composer install monolog/monolog
and change Foo
to
class Foo
{
private $cacheItemPool;
private $bar;
public function __construct(
CacheItemPoolInterface $cacheItemPool,
Bar $bar
) {
$this->cacheItemPool = $cacheItemPool;
$this->bar = $bar;
}
public function resolve(string $someValue): mixed
{
$cacheKey = urlencode("bar/$someValue");
$cacheItem = $this->cacheItemPool->getItem($cacheKey);
if (!$cacheItem->isHit()) {
$cacheItem->set($this->bar->getBySomeValue($someValue));
$cacheItem->expiresAfter(new DateInterval('P1D'));
$this->cacheItemPool->save($cacheItem);
}
return $cacheItem->get();
}
}
Top comments (1)
Great article!
in my opinion, caches should be transparent and outside objects
See sample here
Code Smell 49 - Caches
Maxi Contieri ・ Dec 11 '20 ・ 1 min read