Files
zhamao-framework/src/ZM/Store/Redis/ZMRedis.php

50 lines
1.2 KiB
PHP
Raw Normal View History

<?php /** @noinspection PhpUnused */
/** @noinspection PhpComposerExtensionStubsInspection */
2020-11-03 21:02:24 +08:00
namespace ZM\Store\Redis;
use Redis;
use ZM\Exception\NotInitializedException;
class ZMRedis
{
private $conn;
/**
* @param callable $callable
* @return mixed
* @throws NotInitializedException
*/
public static function call(callable $callable) {
2021-02-09 17:09:09 +08:00
if (ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized.");
2020-11-03 21:02:24 +08:00
$r = ZMRedisPool::$pool->get();
$result = $callable($r);
if (isset($r->wasted)) ZMRedisPool::$pool->put(null);
else ZMRedisPool::$pool->put($r);
return $result;
}
/**
* ZMRedis constructor.
* @throws NotInitializedException
*/
public function __construct() {
2021-02-09 17:09:09 +08:00
if (ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized.");
2020-11-03 21:02:24 +08:00
$this->conn = ZMRedisPool::$pool->get();
}
/**
* @return Redis
*/
public function get(): Redis {
2020-11-03 21:02:24 +08:00
return $this->conn;
}
public function __destruct() {
if (isset($this->conn->wasted)) ZMRedisPool::$pool->put(null);
else ZMRedisPool::$pool->put($this->conn);
}
}