1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of slick/orm package |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Slick\Orm\Repository; |
11
|
|
|
|
12
|
|
|
use Slick\Cache\Cache; |
13
|
|
|
use Slick\Cache\CacheStorageInterface; |
14
|
|
|
use Slick\Orm\EntityInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Identity Map |
18
|
|
|
* |
19
|
|
|
* Ensures that each object gets loaded only once by keeping every loaded |
20
|
|
|
* object in a map. Looks up objects using the map when referring to them. |
21
|
|
|
* |
22
|
|
|
* @package Slick\Orm\Repository |
23
|
|
|
*/ |
24
|
|
|
class IdentityMap implements IdentityMapInterface |
25
|
|
|
{ |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var CacheStorageInterface |
29
|
|
|
*/ |
30
|
|
|
protected $cache; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Set an entity |
34
|
|
|
* |
35
|
|
|
* @param EntityInterface $entity |
36
|
|
|
* |
37
|
|
|
* @return self|$this|IdentityMapInterface |
38
|
|
|
*/ |
39
|
|
|
public function set(EntityInterface $entity) |
40
|
|
|
{ |
41
|
|
|
$this->getCache()->set($entity->getId(), $entity); |
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Gets the entity with provided id |
47
|
|
|
* |
48
|
|
|
* @param mixed $entityId |
49
|
|
|
* |
50
|
|
|
* @param null $default |
51
|
|
|
* |
52
|
|
|
* @return null|mixed|EntityInterface |
53
|
|
|
*/ |
54
|
|
|
public function get($entityId, $default = null) |
55
|
|
|
{ |
56
|
|
|
return $this->getCache()->get($entityId, $default); |
57
|
|
|
|
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Remove an entity from identity map |
62
|
|
|
* |
63
|
|
|
* @param mixed $entityId |
64
|
|
|
* |
65
|
|
|
* @return self|$this|IdentityMapInterface |
66
|
|
|
*/ |
67
|
|
|
public function remove($entityId) |
68
|
|
|
{ |
69
|
|
|
$this->getCache()->erase($entityId); |
70
|
|
|
return $this; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Set cache storage for this identity map |
75
|
|
|
* |
76
|
|
|
* @param CacheStorageInterface $cache |
77
|
|
|
* |
78
|
|
|
* @return $this|self|IdentityMap |
79
|
|
|
*/ |
80
|
|
|
public function setCache(CacheStorageInterface $cache) |
81
|
|
|
{ |
82
|
|
|
$this->cache = $cache; |
83
|
|
|
return $this; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Gets cache storage for this identity map |
88
|
|
|
* |
89
|
|
|
* @return CacheStorageInterface |
90
|
|
|
*/ |
91
|
|
|
public function getCache() |
92
|
|
|
{ |
93
|
|
|
if (null == $this->cache) { |
94
|
|
|
$this->setCache(Cache::get(Cache::CACHE_MEMORY)); |
95
|
|
|
} |
96
|
|
|
return $this->cache; |
97
|
|
|
} |
98
|
|
|
} |