1 <?php
2
3 /*
4 * This file is part of the ICanBoogie package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace ICanBoogie\ActiveRecord;
13
14 use ICanBoogie\ActiveRecord;
15
16 /**
17 * Interface for ActiveRecord cache.
18 */
19 interface ActiveRecordCacheInterface
20 {
21 /**
22 * Stores an {@link ActiveRecord} instance in the cache.
23 *
24 * @param ActiveRecord $record
25 */
26 public function store(ActiveRecord $record);
27
28 /**
29 * Retrieves an {@link ActiveRecord} instance from the cache.
30 *
31 * @param int $key
32 *
33 * @return ActiveRecord|null
34 */
35 public function retrieve($key);
36
37 /**
38 * Eliminates an {@link ActiveRecord} instance from the cache.
39 *
40 * @param int $key
41 */
42 public function eliminate($key);
43
44 /**
45 * Clears the cache.
46 */
47 public function clear();
48 }
49
50 /**
51 * Abstract root class for an active records cache.
52 */
53 abstract class ActiveRecordCache implements ActiveRecordCacheInterface
54 {
55 /**
56 * Model using the cache.
57 *
58 * @var Model
59 */
60 protected $model;
61
62 public function __construct(Model $model)
63 {
64 $this->model = $model;
65 }
66 }
67
68 /**
69 * Cache records during run time.
70 */
71 class RunTimeActiveRecordCache extends ActiveRecordCache implements \IteratorAggregate
72 {
73 /**
74 * Cached records.
75 *
76 * @var ActiveRecord[]
77 */
78 protected $records = [];
79
80 public function store(ActiveRecord $record)
81 {
82 $key = $record->{ $this->model->primary };
83
84 if (!$key || isset($this->records[$key]))
85 {
86 return;
87 }
88
89 $this->records[$key] = $record;
90 }
91
92 public function retrieve($key)
93 {
94 if (empty($this->records[$key]))
95 {
96 return;
97 }
98
99 return $this->records[$key];
100 }
101
102 public function eliminate($key)
103 {
104 unset($this->records[$key]);
105 }
106
107 public function clear()
108 {
109 $this->records = [];
110 }
111
112 public function getIterator()
113 {
114 return new \ArrayIterator($this->records);
115 }
116 }