HashTrait.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace tw\redis\traits;
  3. use tw\redis\TwRedis;
  4. /**
  5. * 支持 redis hash key 操作的函数, 必须 use 到 Base 的子类中, 因为内部调用了 Base 的虚函数
  6. *
  7. */
  8. trait HashTrait
  9. {
  10. /**
  11. * 获取 hash attr
  12. *
  13. * @param int|string $word
  14. * @param string $attr
  15. * @return string
  16. */
  17. public function hget($word, string $attr): string
  18. {
  19. return TwRedis::hGet($this->key($word), $attr);
  20. }
  21. public function hmget($word, array $attrs): array
  22. {
  23. return TwRedis::hMGet($this->key($word), $attrs);
  24. }
  25. /**
  26. * set hash attr
  27. */
  28. public function hset($word, string $attr, $value): bool
  29. {
  30. if (is_array($value)) {
  31. $value = json_encode($value);
  32. }
  33. return TwRedis::hSet($this->key($word), $attr, $value);
  34. }
  35. /**
  36. * 设置多个 attr
  37. *
  38. * @param array $attrs: ['attr1'=>'value1', 'attr2' => 'value2']
  39. * @return bool
  40. */
  41. public function hmset($word, array $attrs): bool
  42. {
  43. return TwRedis::hMSet($this->key($word), $attrs);
  44. }
  45. /**
  46. * setup hash value if the attr not exists
  47. */
  48. public function hsetnx($word, $attr, $val): bool
  49. {
  50. return TwRedis::hSetNx($this->key($word), $attr, $val);
  51. }
  52. /**
  53. * hash 的 attr 是否存在
  54. */
  55. public function hexists($word, string $attr): bool
  56. {
  57. return TwRedis::hExists($this->key($word), $attr);
  58. }
  59. public function hincr_by($word, string $attr, int $step): int
  60. {
  61. return TwRedis::hIncrBy($this->key($word), $attr, $step);
  62. }
  63. public function hincr_by_float($word, string $attr, float $f): float
  64. {
  65. return TwRedis::hIncrByFloat($this->key($word), $attr, $f);
  66. }
  67. public function hkeys($word): array
  68. {
  69. return TwRedis::hKeys($this->key($word));
  70. }
  71. public function hvals($word): array
  72. {
  73. return TwRedis::hVals($this->key($word));
  74. }
  75. public function hmdel($word, $attrs): int
  76. {
  77. if (is_string($attrs)) {
  78. return TwRedis::hDel($this->key($word), $attrs);
  79. } else if (is_array($attrs)) {
  80. return TwRedis::hDel($this->key($word), ...$attrs);
  81. }
  82. }
  83. public function hget_all($word): array
  84. {
  85. return TwRedis::hGetAll($this->key($word));
  86. }
  87. }