1
|
|
|
<?php |
2
|
|
|
namespace PhpDraft\Domain\Services; |
3
|
|
|
|
4
|
|
|
use Silex\Application; |
5
|
|
|
use Symfony\Component\HttpFoundation\Request; |
6
|
|
|
use phpFastCache\CacheManager; |
7
|
|
|
|
8
|
|
|
//A wrapper service for the PHP-based caching to save on several MySQL reads |
9
|
|
|
class DatabaseCacheService { |
10
|
|
|
private $cacheInstance; |
11
|
|
|
|
12
|
|
|
public function __construct(Application $app) { |
13
|
|
|
$this->app = $app; |
|
|
|
|
14
|
|
|
|
15
|
|
|
$cacheConfig = [ |
16
|
|
|
'path' => CACHE_PATH |
17
|
|
|
]; |
18
|
|
|
|
19
|
|
|
$this->cacheInstance = CacheManager::Files($cacheConfig); |
|
|
|
|
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/* |
23
|
|
|
* Attempt to load a cached instance of an object. |
24
|
|
|
* @param string $itemKey The unique identifier of the object in the cache |
25
|
|
|
* @return object the cached object, or null if $itemKey was a miss in the cache |
26
|
|
|
*/ |
27
|
|
|
public function GetCachedItem($itemKey) { |
28
|
|
|
$cachedItem = $this->_LoadCacheObject($itemKey); |
29
|
|
|
|
30
|
|
|
if(!$cachedItem->isHit()) { |
31
|
|
|
return null; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return $cachedItem->get(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/* |
38
|
|
|
* Store an object in the cache for |
39
|
|
|
* @param string $itemKey The unique identifier of the object in the cache |
40
|
|
|
* @param object $item The object that is to be stored in the cache |
41
|
|
|
*/ |
42
|
|
|
public function SetCachedItem($itemKey, $item) { |
43
|
|
|
$cachedItem = $this->_LoadCacheObject($itemKey); |
44
|
|
|
|
45
|
|
|
$cachedItem->set($item)->expiresAfter(CACHE_SECONDS); |
46
|
|
|
$this->cacheInstance->save($cachedItem); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/* |
50
|
|
|
* Remove an object from the cache |
51
|
|
|
* @param string $itemKey The unique identifier of the object in the cache |
52
|
|
|
*/ |
53
|
|
|
public function DeleteCachedItem($itemKey) { |
54
|
|
|
$this->cacheInstance->deleteItem($itemKey); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/* |
58
|
|
|
* Load a phpFastCache cache object for a given key. Is used in both get and set events. |
59
|
|
|
* @param string $itemKey The unique identifier of the object in the cache |
60
|
|
|
* @return object the phpFastCache object for the given key |
61
|
|
|
*/ |
62
|
|
|
private function _LoadCacheObject($itemKey) { |
63
|
|
|
return $this->cacheInstance->getItem($itemKey); |
64
|
|
|
} |
65
|
|
|
} |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: