| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace tw\redis\traits;
- use tw\redis\TwRedis;
- /**
- * 支持 redis hash key 操作的函数, 必须 use 到 Base 的子类中, 因为内部调用了 Base 的虚函数
- *
- */
- trait HashTrait
- {
- /**
- * 获取 hash attr
- *
- * @param int|string $word
- * @param string $attr
- * @return string
- */
- public function get($word, string $attr): string
- {
- return TwRedis::hGet($this->key($word), $attr);
- }
- public function gets($word, array $attrs): array
- {
- return TwRedis::hMGet($this->key($word), $attrs);
- }
- /**
- * set hash attr
- */
- public function set($word, string $attr, $value): bool
- {
- if (is_array($value)) {
- $value = json_encode($value);
- }
- return TwRedis::hSet($this->key($word), $attr, $value);
- }
- /**
- * 设置多个 attr
- *
- * @param array $attrs: ['attr1'=>'value1', 'attr2' => 'value2']
- * @return bool
- */
- public function sets($word, array $attrs): bool
- {
- return TwRedis::hMSet($this->key($word), $attrs);
- }
- /**
- * setup hash value if the attr not exists
- */
- public function hsetnx($word, $attr, $val): bool
- {
- return TwRedis::hSetNx($this->key($word), $attr, $val);
- }
- /**
- * hash 的 attr 是否存在
- */
- public function hexists($word, string $attr): bool
- {
- return TwRedis::hExists($this->key($word), $attr);
- }
- public function hincr_by($word, string $attr, int $step): int
- {
- return TwRedis::hIncrBy($this->key($word), $attr, $step);
- }
- public function hincr_by_float($word, string $attr, float $f): float
- {
- return TwRedis::hIncrByFloat($this->key($word), $attr, $f);
- }
- public function hkeys($word): array
- {
- return TwRedis::hKeys($this->key($word));
- }
- public function hvals($word): array
- {
- return TwRedis::hVals($this->key($word));
- }
- public function dels($word, $attrs): int
- {
- if (is_string($attrs)) {
- return TwRedis::hDel($this->key($word), $attrs);
- } else if (is_array($attrs)) {
- return TwRedis::hDel($this->key($word), ...$attrs);
- }
- }
- public function getAll($word): array
- {
- return TwRedis::hGetAll($this->key($word));
- }
- }
|