123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace app\services\other;
- use app\dao\other\CacheDao;
- use app\services\BaseServices;
- class CacheServices extends BaseServices
- {
- public function __construct(CacheDao $dao)
- {
- $this->dao = $dao;
- }
-
- public function getDbCache(string $key, $default, int $expire = 0)
- {
- $this->dao->delectDeOverdueDbCache();
- $result = $this->dao->value(['key' => $key], 'result');
- if ($result) {
- return json_decode($result, true);
- } else {
- if ($default instanceof \Closure) {
-
- $value = $default();
- if ($value) {
- $this->setDbCache($key, $value, $expire);
- return $value;
- }
- } else {
- $this->setDbCache($key, $default, $expire);
- return $default;
- }
- return null;
- }
- }
-
- public function setDbCache(string $key, $result, $expire = 0)
- {
- $this->dao->delectDeOverdueDbCache();
- $addTime = $expire ? time() + $expire : 0;
- if ($this->dao->count(['key' => $key])) {
- return $this->dao->update($key, [
- 'result' => json_encode($result),
- 'expire_time' => $addTime,
- 'add_time' => time()
- ], 'key');
- } else {
- return $this->dao->save([
- 'key' => $key,
- 'result' => json_encode($result),
- 'expire_time' => $addTime,
- 'add_time' => time()
- ]);
- }
- }
-
- public function delectDbCache(string $key = '')
- {
- if ($key)
- return $this->dao->delete($key, 'key');
- else
- return false;
- }
- }
|