Skip to content

Instantly share code, notes, and snippets.

@danilopinotti
Created September 28, 2022 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilopinotti/83926303d4e751bb32813b6ddae96202 to your computer and use it in GitHub Desktop.
Save danilopinotti/83926303d4e751bb32813b6ddae96202 to your computer and use it in GitHub Desktop.
Implements a layer above objects that caches all method calls
<?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