1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Util |
4
|
|
|
* |
5
|
|
|
* @copyright Copyright (c) Gjero Krsteski (http://krsteski.de) |
6
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Pimf\Util; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* The identity map pattern is a database access design pattern used to improve performance |
13
|
|
|
* by providing a context-specific, in-memory cache to prevent duplicate retrieval of the |
14
|
|
|
* same object data from the database. |
15
|
|
|
* |
16
|
|
|
* @package Util |
17
|
|
|
* @author Gjero Krsteski <[email protected]> |
18
|
|
|
*/ |
19
|
|
|
class IdentityMap |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var \ArrayObject |
23
|
|
|
*/ |
24
|
|
|
protected $idToObject; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var \SplObjectStorage |
28
|
|
|
*/ |
29
|
|
|
protected $objectToId; |
30
|
|
|
|
31
|
|
|
public function __construct() |
32
|
|
|
{ |
33
|
|
|
$this->objectToId = new \SplObjectStorage(); |
34
|
|
|
$this->idToObject = new \ArrayObject(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param integer $key |
39
|
|
|
* @param mixed $object |
40
|
|
|
*/ |
41
|
|
|
public function set($key, $object) |
42
|
|
|
{ |
43
|
|
|
$this->idToObject[$key] = $object; |
44
|
|
|
$this->objectToId[$object] = $key; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param mixed $object |
49
|
|
|
* |
50
|
|
|
* @throws \OutOfBoundsException |
51
|
|
|
* @return integer |
52
|
|
|
*/ |
53
|
|
|
public function getId($object) |
54
|
|
|
{ |
55
|
|
|
if (false === $this->hasObject($object)) { |
56
|
|
|
throw new \OutOfBoundsException('no object=' . get_class($object) . ' at the identity-map'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $this->objectToId[$object]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param integer $key |
64
|
|
|
* |
65
|
|
|
* @return boolean |
66
|
|
|
*/ |
67
|
|
|
public function hasId($key) |
68
|
|
|
{ |
69
|
|
|
return isset($this->idToObject[$key]); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param mixed $object |
74
|
|
|
* |
75
|
|
|
* @return boolean |
76
|
|
|
*/ |
77
|
|
|
public function hasObject($object) |
78
|
|
|
{ |
79
|
|
|
return isset($this->objectToId[$object]); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param integer $key |
84
|
|
|
* |
85
|
|
|
* @throws \OutOfBoundsException |
86
|
|
|
* @return object |
87
|
|
|
*/ |
88
|
|
|
public function getObject($key) |
89
|
|
|
{ |
90
|
|
|
if (false === $this->hasId($key)) { |
91
|
|
|
throw new \OutOfBoundsException('no id=' . $key . ' at the identity-map'); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
return $this->idToObject[$key]; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|