Created
June 4, 2020 16:29
-
-
Save szepeviktor/d4a8d17769b35fc9e9f2b78c3886a37e to your computer and use it in GitHub Desktop.
🐒 ArrayAccess implementáció cache-eléshez 🐒
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 | |
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