Fixing a weird issue with Symfony's Cache


I'm just getting started with Symfony, so I'm blogging some of the weird things I'm finding.

Symfony has a concept of Cache Contracts. You can call an expensive / slow / intensive operation and immediately cache the result for a specific time period. Next time you call the operation, the results are served from the cache until the expiry time has been hit.

Nifty! But I couldn't get it to work.

Take this sample code. It should return the current date and time and cache the result for 5 minutes (300 seconds). If you call it repeatedly, it should keep showing the old date until the 5 minutes are up.

<?php
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

class Whatever
{
    public function get_date() {
        $cache = new FilesystemAdapter();
        $value = $cache->get('cached_date', function (ItemInterface $item) {
            $item->expiresAfter(300);
            $date = date("Y-m-d H:i:s");
            return $date;
      });
      return $value;
    }
}

But it wasn't working. Why? I don't know. But I fixed it by using a namespaced cache:

$cache = new FilesystemAdapter("my_awesome_cache");

I hope that's helpful to someone - even if that someone is me in a few years' time!


Share this post on…

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">