RedisFlat.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace loyalsoft\Util;
  3. /**
  4. * 将对象在Redis中进行扁平化存储(即将对象的一级属性拆分到hash中存储,属性值仍然采用json编码)
  5. * @author gwang
  6. */
  7. trait RedisFlat {
  8. /**
  9. * 魔术方法的运用,增加类似于 $obj->name()这样的调用方法,能够直接将属性当做方法用(内部是取数据方法)
  10. * @param type $name
  11. * @param type $arguments
  12. * @return type
  13. */
  14. public function __call($name, $arguments) {
  15. if (array_key_exists("$name", $this)) {
  16. if (!isset($this->dicSaveflags) or ! is_array($this->dicSaveflags)) {
  17. $this->dicSaveflags = array();
  18. }
  19. if (isset($arguments[0])and $arguments[0]) {
  20. $this->dicSaveflags[] = $name;
  21. }
  22. if (!isset($this->$name)) {
  23. $this->$name = $this->readPropertyFromMem($name);
  24. }
  25. }
  26. return $this->$name;
  27. }
  28. /**
  29. * 对象实例必须有获取/指定自己在Mem中的key的方法
  30. */
  31. abstract function getMemKey();
  32. /**
  33. * @return $this 从Mem中初始化对象
  34. */
  35. function ReadAllPropertyFromMem() {
  36. foreach ($this as $name => $value) {
  37. if ($name == self::$_ext) {
  38. continue;
  39. }
  40. $v = $this->readPropertyFromMem($name);
  41. if (!empty($v)) {
  42. $this->$name = $v;
  43. }
  44. }
  45. return $this;
  46. }
  47. /**
  48. * 将对象数据写会mem
  49. */
  50. function updateData() {
  51. $key = $this->getMemKey();
  52. \loyalsoft\gMem()->hmset($key, $this->getDict());
  53. }
  54. /**
  55. * @return array 将$this转成ASSOC_Array(string propertyName,json proptertyValue)
  56. */
  57. private function getDict() {
  58. $arr = array();
  59. foreach ($this as $key => $value) {
  60. if ($key == self::$_ext) {
  61. continue;
  62. }
  63. if (isset($this->dicSaveflags) and in_array($key, $this->dicSaveflags)) { # 只关注做了保存标记的
  64. $arr[$key] = JsonUtil::encode($value);
  65. } else { # 数组未初始化的情况下全部提取
  66. $arr[$key] = JsonUtil::encode($value);
  67. }
  68. }
  69. return $arr;
  70. }
  71. /**
  72. * 读取单独的key的方法
  73. * @param type $name
  74. * @return type
  75. */
  76. private function readPropertyFromMem($name) {
  77. $key = $this->getMemKey();
  78. return \loyalsoft\gMem()->hget($key, $name);
  79. }
  80. /**
  81. * @var string 特定字段名称,将被排除在序列化之外
  82. */
  83. private static $_ext = "dicSaveflags";
  84. /**
  85. * @var array[string] 保存标记数组
  86. */
  87. protected $dicSaveflags;
  88. }