Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Created May 11, 2025 04:00
Show Gist options
  • Save DarkGhostHunter/a115f67df3d2c232517a08a17caa7d00 to your computer and use it in GitHub Desktop.
Save DarkGhostHunter/a115f67df3d2c232517a08a17caa7d00 to your computer and use it in GitHub Desktop.
A cache repository for objects
<?php
namespace App\Repository;
use Closure;
use Illuminate\Contracts\Cache\Factory as CacheFactoryContract;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use InvalidArgumentException;
use function trim;
class Repository
{
/**
* The default prefix for the cache keys.
*/
protected const DEFAULT_PREFIX = 'stash';
/**
* Create a new Repository instance.
*/
public function __construct(
protected CacheFactoryContract $factory,
protected string $prefix = self::DEFAULT_PREFIX,
protected ?string $store = null,
protected array $callbacks = [],
) {
//
}
/**
* Sets the Cache store to use.
*
* @return $this
*/
public function store(string $store): static
{
$this->store = $store;
return $this;
}
/**
* Return the cache repository implementation.
*/
protected function cache(): CacheRepository
{
return $this->factory->store($this->store);
}
/**
* Return the concatenated key to use with the Cache Repository.
*/
protected function key(string $key): string
{
return $this->prefix . '|' . trim($key, '|');
}
/**
* Saves a callback to be executed as part of the cache.
*/
public function set(string $key, callable $callback): void
{
$this->callbacks[$key] = $callback;
}
/**
* Retrieve the closure from the cache or fail.
*/
protected function closure(string $key): Closure
{
return $this->callbacks[$key] ?? throw new InvalidArgumentException("No stash found for key [$key].");
}
/**
* Return the callback execution
*/
public function get(string $key): mixed
{
return $this->cache()->rememberForever($this->key($key), fn(): mixed => ($this->closure($key))());
}
/**
* Check if the callback exists in the cache.
*/
public function has(string $key): bool
{
return isset($this->callbacks[$key]);
}
/**
* Check if the callback is missing from the cache.
*/
public function missing(string $key): bool
{
return ! $this->has($key);
}
/**
* Removes the callback and value from the cache.
*/
public function remove(string $key): void
{
unset($this->callbacks[$key]);
$this->cache()->forget($this->key($key));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment