-
Notifications
You must be signed in to change notification settings - Fork 482
Yii2 adapter cache for device detector
Tutik Alexsandr edited this page Jan 25, 2023
·
1 revision
- create dirs
helpers/DeviceDetector
for root project and create fileCache.php
- copy next code and put to
Cache.php
file
<?php
namespace app\helpers\DeviceDetector;
use DeviceDetector\Cache\CacheInterface;
use Yii;
/**
* Class Cache
* @package app\helpers\DeviceDetector
*/
class Cache implements CacheInterface
{
/**
* @var string - cache section name for config/web.php
*/
public $name = 'cache';
/**
* @return yii\caching\FileCache|\yii\redis\Cache
* @throws \yii\base\InvalidConfigException
*/
private function getCache()
{
return Yii::$app->get($this->name, true);
}
/**
* @param string $id
* @return bool
* @throws \yii\base\InvalidConfigException
*/
public function contains(string $id): bool
{
return $this->getCache()->get($id) !== false;
}
/**
* @param string $id
* @return bool|false|mixed
* @throws \yii\base\InvalidConfigException
*/
public function fetch(string $id)
{
return $this->getCache()->get($id);
}
/**
* @param string $id
* @return bool
* @throws \yii\base\InvalidConfigException
*/
public function delete(string $id): bool
{
return $this->getCache()->delete($id);
}
/**
* @return bool
* @throws \yii\base\InvalidConfigException
*/
public function flushAll(): bool
{
return $this->getCache()->flush();
}
/**
* @param string $id
* @param mixed $data
* @param int $lifeTime
* @return bool
* @throws \yii\base\InvalidConfigException
*/
public function save(string $id, $data, int $lifeTime = 0): bool
{
return $this->getCache()->set($id, $data, $lifeTime);
}
}
usage
$detector = new DeviceDetector();
$detector->setCache(new Cache([
'name' => 'redis'
]));
$detector->skipBotDetection();