Working with Symfony Cache¶
Here is a quick run down of how to work with the cache in your code
Inject the Dependency into your Class¶
in your constructor, inject the CacheItemPoolInterface $cache
and assign to $this->cache
Use the Cache¶
Cache Key as Constant¶
First you need to define a cache key. This should be a class constant,
private const THING_CACHE_KEY='the-thing';
Optional Class Level Cache Property¶
For small things that might be requested multiple times, you should cache on the class instance with a property.
For large things, you need to think about over caching as you might be baking in memory issues.
When you use this approach, the actual cache should only be loaded once per request.
The Getter Method¶
The getter method handles the caching logic and the updating of the class level cache property
The Expensive Loading Method¶
If we get a cold cache and need to actually load the thing, then do this in a separate private method
Preventing Cache in Dev¶
If you want to prevent cache loading in dev, you can handle this
Example Class With Caching for theThing
¶
<?php
declare(strict_types=1);
namespace MyProject\Helper;
use Psr\Cache\CacheItemPoolInterface;
class TheThingGetter{
/**
* The cache key should be a class constant
*/
private const THING_CACHE_KEY='the-thing';
/**
* @var CacheItemPoolInterface
*/
private $cache;
/**
* This is a class level cache of the thing, so we only retrieve from the actual cache once.
* For small things this makes sense.
* Larger things that might take up too much memory should not be cached this way.
* @var array
*/
private $theThing;
/**
* @var EnvironmentHelper
*/
private $environmentHelper;
public function __construct(CacheItemPoolInterface $cache, EnvironmentHelper $environmentHelper){
$this->cache = $cache;
$this->environmentHelper = $environmentHelper
}
public function getTheThing():array{
if (null !== $this->theThing) {
return $this->theThing;
}
if($this->)
$cache = $this->cache->getItem(self::CACHE_KEY);
if ($cache->isHit()) {
// set our cache loaded value to the class for faster retrieval in future
$this->theThing = $cache->get();
return $this->theThing;
}
// it wasn't cache so we now have to load it and assign to the class
$this->theThing=$this->expensiveLoadTheThingMethod();
// now we save it to the cache
$cache->set($this->theThing);
return $this->theThing;
}
private function expensiveLoadTheThingMethod():array{
// do stuff to load the thing
}
}