Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Last active March 21, 2023 17:18
Show Gist options
  • Save AnandPilania/1d6ca87caede067f7125ce83d52b8f5a to your computer and use it in GitHub Desktop.
Save AnandPilania/1d6ca87caede067f7125ce83d52b8f5a to your computer and use it in GitHub Desktop.
Laravel memorize once in a request
<?php
/** @.template T
* @.param T target
* @.return T
*/
function memorize($target) {
static $memo = new WeakMap;
return new class ($target, $memo) {
function __construct(
protected $target,
protected &$memo,
) {}
function __call($method, $params)
{
$this->memo[$this->target] ??= [];
$signature = $method . crc32(json_encode($params));
return $this->memo[$this->target][$signature]
??= $this->target->$method(...$params);
}
};
}
<?php
class MemorizeClass
{
function __construct(
protected $target,
protected &$memo,
) {}
public function __call($method, $params)
{
$this->memo[$this->target] ??= [];
$signature = $method . crc32(json_encode($params));
return $this->memo[$this->target][$signature]
??= $this->target->$method(...$params);
}
}
@AnandPilania
Copy link
Author

$viewCount = memorize(auth()->user())->getViewCount();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment