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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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
    }
}