Created
September 28, 2022 15:27
-
-
Save danilopinotti/83926303d4e751bb32813b6ddae96202 to your computer and use it in GitHub Desktop.
Implements a layer above objects that caches all method calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support; | |
class HighOrderCacheProxy | |
{ | |
protected string $ttl = '15 minutes'; | |
protected array $tags = []; | |
public function __construct( | |
protected $target, | |
protected string $cachePrefix = '', | |
protected string $cacheSuffix = '', | |
) { | |
} | |
public function ttl(string $ttl): self | |
{ | |
$this->ttl = $ttl; | |
return $this; | |
} | |
public function tags(array $tags): self | |
{ | |
$this->tags = $tags; | |
return $this; | |
} | |
public function __call($method, $args) | |
{ | |
$result = function () use ($method, $args) { | |
return $this->target->$method(...$args); | |
}; | |
$prefix = trim($this->cachePrefix, ':') | |
?: get_class($this->target); | |
$key = sprintf( | |
'%s:%s:%s', | |
$prefix, | |
$method . '@' . substr(\sha1(\json_encode($args)), 0, 8), | |
trim($this->cacheSuffix, ':') | |
); | |
return cache_manager($key, $this->ttl, $result, $this->tags); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment