|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace AppBundle\Helper; |
|
4
|
|
|
|
|
5
|
|
|
use DateInterval; |
|
6
|
|
|
use Symfony\Component\DependencyInjection\Container; |
|
7
|
|
|
|
|
8
|
|
|
abstract class HelperBase |
|
9
|
|
|
{ |
|
10
|
|
|
|
|
11
|
|
|
/** @var Container */ |
|
12
|
|
|
protected $container; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Get a cache key. |
|
16
|
|
|
* @param string $key |
|
17
|
|
|
* @return string The key with a representation of the class name prefixed. |
|
18
|
|
|
*/ |
|
19
|
|
|
private function getCacheKey($key) |
|
20
|
|
|
{ |
|
21
|
|
|
return str_replace('\\', '', get_class($this)).'.'.$key; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Find out whether the given key exists in the cache. |
|
26
|
|
|
* @param string $key The cache key. |
|
27
|
|
|
* @return boolean |
|
28
|
|
|
*/ |
|
29
|
|
|
protected function cacheHas($key) |
|
30
|
|
|
{ |
|
31
|
|
|
/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */ |
|
32
|
|
|
$cache = $this->container->get('cache.app'); |
|
33
|
|
|
return $cache->getItem($this->getCacheKey($key))->isHit(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Get a value from the cache. With this it is not possible to tell the difference between a |
|
38
|
|
|
* cached value of 'null' and there being no cached value; if that situation is likely, you |
|
39
|
|
|
* should use the cache service directly. |
|
40
|
|
|
* @param string $key The cache key. |
|
41
|
|
|
* @return mixed|null Whatever's in the cache, or null if the key isn't present. |
|
42
|
|
|
*/ |
|
43
|
|
|
protected function cacheGet($key) |
|
44
|
|
|
{ |
|
45
|
|
|
/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */ |
|
46
|
|
|
$cache = $this->container->get('cache.app'); |
|
47
|
|
|
$item = $cache->getItem($this->getCacheKey($key)); |
|
48
|
|
|
if ($item->isHit()) { |
|
49
|
|
|
return $item->get(); |
|
50
|
|
|
} |
|
51
|
|
|
return null; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Save a value to the cache. |
|
56
|
|
|
* @param string $key The cache key. |
|
57
|
|
|
* @param string $value The value to cache. |
|
58
|
|
|
* @param string $expiresAfter A DateInterval interval specification. |
|
59
|
|
|
*/ |
|
60
|
|
|
protected function cacheSave($key, $value, $expiresAfter) |
|
61
|
|
|
{ |
|
62
|
|
|
/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */ |
|
63
|
|
|
$cache = $this->container->get('cache.app'); |
|
64
|
|
|
$item = $cache->getItem($this->getCacheKey($key)); |
|
65
|
|
|
$item->set($value); |
|
66
|
|
|
$item->expiresAfter(new DateInterval($expiresAfter)); |
|
67
|
|
|
$cache->save($item); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|