forked from phpnode/YiiRedis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ARedisCounter.php
executable file
·75 lines (70 loc) · 2.06 KB
/
ARedisCounter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Represents a redis counter that can be atomically incremented and decremented.
* <pre>
* $counter = new ARedisCounter("totalPageViews");
* $counter->increment();
* echo $counter->getValue();
* </pre>
* @author Charles Pick
* @package packages.redis
*/
class ARedisCounter extends ARedisEntity {
/**
* The value of the counter
* @var integer
*/
protected $_value;
/**
* Removes all the items from the entity
* @return ARedisIterableEntity the current entity
*/
public function clear() {
$this->_value = null;
$this->getConnection()->getClient()->delete($this->name);
return $this;
}
/**
* Gets the value of the counter
* @param boolean $forceRefresh whether to fetch the data from redis again or not
* @return integer the value of the counter
*/
public function getValue($forceRefresh = false) {
if ($this->_value === null || $forceRefresh) {
if ($this->name === null) {
throw new CException(get_class($this)." requires a name!");
}
$this->_value = (int) $this->getConnection()->getClient()->get($this->name);
}
return $this->_value;
}
/**
* Increments the counter by the given amount
* @param integer $byAmount the amount to increment by, defaults to 1
* @return integer the new value of the counter
*/
public function increment($byAmount = 1) {
if ($this->name === null) {
throw new CException(get_class($this)." requires a name!");
}
return $this->_value = (int) $this->getConnection()->getClient()->incrBy($this->name,$byAmount);
}
/**
* Decrements the counter by the given amount
* @param integer $byAmount the amount to decrement by, defaults to 1
* @return integer the new value of the counter
*/
public function decrement($byAmount = 1) {
if ($this->name === null) {
throw new CException(get_class($this)." requires a name!");
}
return $this->_value = (int) $this->getConnection()->getClient()->decrBy($this->name,$byAmount);
}
/**
* Gets the value of the counter
* @return integer the value of the counter
*/
public function __toString() {
return $this->getValue();
}
}