HashTrait.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 get($word, string $attr): string
  18. {
  19. return TwRedis::hGet($this->key($word), $attr);
  20. }
  21. public function gets($word, array $attrs): array
  22. {
  23. return TwRedis::hMGet($this->key($word), $attrs);
  24. }
  25. /**
  26. * set hash attr
  27. */
  28. public function set($word, string $attr, $value): bool
  29. {
  30. return TwRedis::hSet($this->key($word), $attr, $value);
  31. }
  32. /**
  33. * 设置多个 attr
  34. *
  35. * @param array $attrs: ['attr1'=>'value1', 'attr2' => 'value2']
  36. * @return bool
  37. */
  38. public function sets($word, array $attrs): bool
  39. {
  40. return TwRedis::hMSet($this->key($word), $attrs);
  41. }
  42. /**
  43. * setup hash value if the attr not exists
  44. */
  45. public function hsetnx($word, $attr, $val): bool
  46. {
  47. return TwRedis::hSetNx($this->key($word), $attr, $val);
  48. }
  49. /**
  50. * hash 的 attr 是否存在
  51. */
  52. public function hexists($word, string $attr): bool
  53. {
  54. return TwRedis::hExists($this->key($word), $attr);
  55. }
  56. public function hincr_by($word, string $attr, int $step): int
  57. {
  58. return TwRedis::hIncrBy($this->key($word), $attr, $step);
  59. }
  60. public function hincr_by_float($word, string $attr, float $f): float
  61. {
  62. return TwRedis::hIncrByFloat($this->key($word), $attr, $f);
  63. }
  64. public function hkeys($word): array
  65. {
  66. return TwRedis::hKeys($this->key($word));
  67. }
  68. public function hvals($word): array
  69. {
  70. return TwRedis::hVals($this->key($word));
  71. }
  72. public function dels($word, $attrs): int
  73. {
  74. if (is_string($attrs)) {
  75. return TwRedis::hDel($this->key($word), $attrs);
  76. } else if (is_array($attrs)) {
  77. return TwRedis::hDel($this->key($word), ...$attrs);
  78. }
  79. }
  80. public function getAll($word): array
  81. {
  82. return TwRedis::hGetAll($this->key($word));
  83. }
  84. }