You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

79 lines
1.8 KiB

  1. <?php
  2. namespace Kuxin\Cache;
  3. use Kuxin\Config;
  4. use Kuxin\Helper\Serialize;
  5. class Memcached
  6. {
  7. /**
  8. * @var \Memcached
  9. */
  10. protected $handler;
  11. /**
  12. * @var string 缓存前缀
  13. */
  14. protected $prefix = '';
  15. public function __construct(array $option)
  16. {
  17. if (!extension_loaded('memcached')) {
  18. trigger_error('您尚未安装memcached扩展', E_USER_ERROR);
  19. }
  20. $this->handler = new \Memcached();
  21. $this->handler->addServer($option['host'] ?? '127.0.0.1', $option['port'] ?? '11211');
  22. $this->prefix = $option['prefix'] ?? Config::get('cache.prefix', '');
  23. }
  24. public function set(string $key, $value, ?int $time = 0)
  25. {
  26. return $this->handler->set($this->prefix . $key, Serialize::encode($value), $time);
  27. }
  28. public function get(string $key)
  29. {
  30. $return = $this->handler->get($this->prefix . $key);
  31. if ($return === false) {
  32. return null;
  33. } elseif (is_string($return)) {
  34. return Serialize::decode($return);
  35. } else {
  36. return $return;
  37. }
  38. }
  39. public function remove(string $key)
  40. {
  41. return $this->handler->delete($this->prefix . $key);
  42. }
  43. public function inc(string $key, int $num = 1)
  44. {
  45. $key = $this->prefix . $key;
  46. if ($this->handler->get($key)) {
  47. return $this->handler->increment($key, $num);
  48. }
  49. $this->handler->set($key, $num);
  50. return $num;
  51. }
  52. public function dec(string $key, int $num = 1)
  53. {
  54. $key = $this->prefix . $key;
  55. if ($this->handler->get($key)) {
  56. return $this->handler->decrement($key, $num);
  57. } else {
  58. $this->handler->set($key, 0);
  59. return 0;
  60. }
  61. }
  62. public function clear()
  63. {
  64. $this->handler->flush();
  65. }
  66. }