DEV Community

Cover image for Write clean & good code - correct caching in PHP
Mati Andreas
Mati Andreas

Posted on

Write clean & good code - correct caching in PHP

Another caching article you think and feel alt text. 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];
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
mcsee profile image
Maxi Contieri

Great article!
in my opinion, caches should be transparent and outside objects

See sample here