Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Created June 4, 2020 16:29
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 szepeviktor/d4a8d17769b35fc9e9f2b78c3886a37e to your computer and use it in GitHub Desktop.
Save szepeviktor/d4a8d17769b35fc9e9f2b78c3886a37e to your computer and use it in GitHub Desktop.
🐒 ArrayAccess implementáció cache-eléshez 🐒
<?php
class KesselőMajom implements ArrayAccess
{
const ARRAY_METHODS = [
'__construct',
'offsetSet',
'offsetExists',
'offsetUnset',
'offsetGet',
];
protected $id;
/**
* @var array<mixed, mixed>
*/
protected $cache;
public function __construct(int $id)
{
$this->id = $id;
$this->cache = [];
}
public function offsetSet($offset, $value): void
{
// Csak adatforrás vagyunk.
}
public function offsetExists($offset): bool
{
return ! \in_array($offset, self::ARRAY_METHODS, true) && \method_exists($this, $offset);
}
public function offsetUnset($offset): void
{
// Csak adatforrás vagyunk.
}
/**
* @return mixed
*/
public function offsetGet($offset)
{
if (! $this->offsetExists($offset)) {
return null;
}
// Megvan, nem kell a drága fgv-t lefuttatni.
if (\array_key_exists($offset, $this->cache)) {
return $this->cache[$offset];
}
// Tankolunk!
$this->cache[$offset] = $this->$offset();
return $this->cache[$offset];
}
protected function bonyiHosszúLekérés(): int
{
return 1 * 1;
}
}
// Ez ingyen van!
$példány = new KesselőMajom(6314);
// Ez tart sokáig:
echo 'A számítás eredménye ', $példány['bonyiHosszúLekérés'], "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment