HashTrait.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. public function sets($word, array $attrs) : bool
  33. {
  34. return TwRedis::hMSet($this->key($word), $attrs);
  35. }
  36. /**
  37. * setup hash value if the attr not exists
  38. */
  39. public function hsetnx($word, $attr, $val) : bool
  40. {
  41. return TwRedis::hSetNx($this->key($word), $attr, $val);
  42. }
  43. /**
  44. * hash 的 attr 是否存在
  45. */
  46. public function hexists($word, string $attr) : bool
  47. {
  48. return TwRedis::hExists($this->key($word), $attr);
  49. }
  50. public function hincr_by($word, string $attr, int $step) : int
  51. {
  52. return TwRedis::hIncrBy($this->key($word), $attr, $step);
  53. }
  54. public function hincr_by_float($word, string $attr, float $f) : float
  55. {
  56. return TwRedis::hIncrByFloat($this->key($word), $attr, $f);
  57. }
  58. public function hkeys($word) : array
  59. {
  60. return TwRedis::hKeys($this->key($word));
  61. }
  62. public function hvals($word) : array
  63. {
  64. return TwRedis::hVals($this->key($word));
  65. }
  66. public function dels($word, $attrs) : int
  67. {
  68. if (is_string($attrs)) {
  69. return TwRedis::hDel($this->key($word), $attrs);
  70. } else if (is_array($attrs)) {
  71. return TwRedis::hDel($this->key($word), ...$attrs);
  72. }
  73. }
  74. public function getAll($word) : array
  75. {
  76. return TwRedis::hGetAll($this->key($word));
  77. }
  78. }