ARedisCounter.php 2.1 KB

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