1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Chief\Decorators; |
4
|
|
|
|
5
|
|
|
use Chief\CacheableCommand; |
6
|
|
|
use Chief\Command; |
7
|
|
|
use Chief\CommandBus; |
8
|
|
|
use Chief\Decorator; |
9
|
|
|
use Psr\Cache\CacheItemPoolInterface; |
10
|
|
|
|
11
|
|
|
class CachingDecorator implements Decorator |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var CommandBus |
15
|
|
|
*/ |
16
|
|
|
private $innerBus; |
17
|
|
|
/** |
18
|
|
|
* @var CacheItemPoolInterface |
19
|
|
|
*/ |
20
|
|
|
private $cache; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* CachingDecorator constructor. |
24
|
|
|
* @param CacheItemPoolInterface $cache |
25
|
|
|
*/ |
26
|
|
|
public function __construct(CacheItemPoolInterface $cache) |
27
|
|
|
{ |
28
|
|
|
$this->cache = $cache; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @inheritdoc |
33
|
|
|
*/ |
34
|
|
|
public function setInnerBus(CommandBus $bus) |
35
|
|
|
{ |
36
|
|
|
$this->innerBus = $bus; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @inheritdoc |
41
|
|
|
*/ |
42
|
|
|
public function execute(Command $command) |
43
|
|
|
{ |
44
|
|
|
if (!$command instanceof CacheableCommand) { |
45
|
|
|
return $this->innerBus->execute($command); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$cached = $this->cache->getItem(self::createCacheKey($command)); |
49
|
|
|
if ($cached->isHit()) { |
50
|
|
|
return $cached->get(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$value = $this->innerBus->execute($command); |
54
|
|
|
|
55
|
|
|
$this->cache->save($this->createCacheItem($command, $value)); |
56
|
|
|
|
57
|
|
|
return $value; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Create a new cache item to be persisted. |
62
|
|
|
* |
63
|
|
|
* @param CacheableCommand $command |
64
|
|
|
* @param mixed $value |
65
|
|
|
* @return CacheItem |
66
|
|
|
*/ |
67
|
|
|
private function createCacheItem(CacheableCommand $command, $value) |
68
|
|
|
{ |
69
|
|
|
return new CacheItem( |
70
|
|
|
$this->createCacheKey($command), |
71
|
|
|
$value, |
72
|
|
|
3600 |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Create the key to be used when saving this item to the cache pool. |
78
|
|
|
* |
79
|
|
|
* The cache item key is taken as a the (string) serialized command, to ensure the return value is unique |
80
|
|
|
* depending on the command properties; that serialized string is then md5'd to ensure it doesn't |
81
|
|
|
* overflow any string length limits the implementing CacheItemPoolInterface library has. |
82
|
|
|
* |
83
|
|
|
* @param CacheableCommand $command |
84
|
|
|
* @return string |
85
|
|
|
*/ |
86
|
|
|
private function createCacheKey(CacheableCommand $command) |
87
|
|
|
{ |
88
|
|
|
return md5(serialize($command)); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|