|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @link https://github.com/lav45/yii2-settings |
|
4
|
|
|
* @copyright Copyright (c) 2016 LAV45 |
|
5
|
|
|
* @author Alexey Loban <[email protected]> |
|
6
|
|
|
* @license http://opensource.org/licenses/BSD-3-Clause |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace lav45\settings\behaviors; |
|
10
|
|
|
|
|
11
|
|
|
use yii\di\Instance; |
|
12
|
|
|
use yii\base\Behavior; |
|
13
|
|
|
use yii\caching\Cache; |
|
14
|
|
|
use lav45\settings\Settings; |
|
15
|
|
|
use lav45\settings\events\GetEvent; |
|
16
|
|
|
use lav45\settings\events\SetEvent; |
|
17
|
|
|
use lav45\settings\events\DeleteEvent; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Class CacheBehavior |
|
21
|
|
|
* @package lav45\settings\behaviors |
|
22
|
|
|
* |
|
23
|
|
|
* @property Settings $owner |
|
24
|
|
|
*/ |
|
25
|
|
|
class CacheBehavior extends Behavior |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* @var Cache|string|array |
|
29
|
|
|
*/ |
|
30
|
|
|
public $cache = 'cache'; |
|
31
|
|
|
/** |
|
32
|
|
|
* @var integer |
|
33
|
|
|
*/ |
|
34
|
|
|
public $cacheDuration = 3600; |
|
35
|
|
|
/** |
|
36
|
|
|
* @var \yii\caching\Dependency |
|
37
|
|
|
*/ |
|
38
|
|
|
public $cacheDependency; |
|
39
|
|
|
|
|
40
|
5 |
|
public function init() |
|
41
|
|
|
{ |
|
42
|
5 |
|
parent::init(); |
|
43
|
5 |
|
$this->cache = clone Instance::ensure($this->cache, Cache::class); |
|
44
|
5 |
|
$this->cache->serializer = false; |
|
45
|
5 |
|
} |
|
46
|
|
|
|
|
47
|
5 |
|
public function events() |
|
48
|
|
|
{ |
|
49
|
|
|
return [ |
|
50
|
5 |
|
Settings::EVENT_BEFORE_GET => 'beforeGetValue', |
|
51
|
|
|
Settings::EVENT_AFTER_GET => 'afterGetValue', |
|
52
|
|
|
Settings::EVENT_AFTER_SET => 'afterSetValue', |
|
53
|
|
|
Settings::EVENT_AFTER_DELETE => 'afterDeleteValue', |
|
54
|
|
|
]; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
5 |
|
public function beforeGetValue(GetEvent $event) |
|
58
|
|
|
{ |
|
59
|
5 |
|
$key = $this->owner->buildKey($event->key); |
|
60
|
5 |
|
$value = $this->cache->get($key); |
|
61
|
5 |
|
if ($value !== false) { |
|
62
|
4 |
|
$event->value = $value; |
|
63
|
|
|
} |
|
64
|
5 |
|
} |
|
65
|
|
|
|
|
66
|
4 |
|
public function afterGetValue(GetEvent $event) |
|
67
|
|
|
{ |
|
68
|
4 |
|
$this->setValue($event->key, $event->value); |
|
69
|
4 |
|
} |
|
70
|
|
|
|
|
71
|
4 |
|
public function afterSetValue(SetEvent $event) |
|
72
|
|
|
{ |
|
73
|
4 |
|
$this->setValue($event->key, $event->value); |
|
74
|
4 |
|
} |
|
75
|
|
|
|
|
76
|
5 |
|
protected function setValue($key, $value) |
|
77
|
|
|
{ |
|
78
|
5 |
|
$this->cache->set($key, $value, $this->cacheDuration, $this->cacheDependency); |
|
79
|
5 |
|
} |
|
80
|
|
|
|
|
81
|
1 |
|
public function afterDeleteValue(DeleteEvent $event) |
|
82
|
|
|
{ |
|
83
|
1 |
|
$this->cache->delete($event->key); |
|
84
|
|
|
} |
|
85
|
|
|
} |