-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathCachingAspect.php
54 lines (45 loc) · 1.56 KB
/
CachingAspect.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
/*
* Go! AOP framework
*
* @copyright Copyright 2014, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Demo\Aspect;
use Demo\Attribute\Cacheable;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Attribute\Around;
/**
* Caching aspect
*/
class CachingAspect implements Aspect
{
/**
* This advice intercepts an execution of cacheable methods
*
* Logic is pretty simple: we look for the value in the cache and if it's not present here
* then invoke original method and store it's result in the cache.
*
* Real-life examples will use APC or Memcache to store value in the cache
*/
#[Around('@execution(Demo\Attribute\Cacheable)')]
protected function aroundCacheable(MethodInvocation $invocation): mixed
{
static $memoryCache = [];
$time = microtime(true);
$obj = $invocation->getThis();
$class = is_object($obj) ? get_class($obj) : $obj;
$key = $class . ':' . $invocation->getMethod()->name;
if (!isset($memoryCache[$key])) {
$attributeArgs = $invocation->getMethod()->getAttributes(Cacheable::class)[0]->getArguments();
echo "Ttl is: ", $attributeArgs['time'], PHP_EOL;
$memoryCache[$key] = $invocation->proceed();
}
echo "Take ", sprintf("%0.3f", (microtime(true) - $time) * 1e3), "ms to call method $key", PHP_EOL;
return $memoryCache[$key];
}
}