A little memoize function in PHP
So, Caleb Porzio recently shared a little memoize function in PHP. What the function does is pretty straightforward.
It caches the result of a function call and returns the cached result if the function is called again with the same arguments.
Here’s the function.
function memoize($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);
}
};
}
And here’s how you can use it.
class User
{
private function getViewCount()
{
return DB::table('users')->count();
}
}
$user = new User;
// saves the result of the first call
$viewCount = memoize($user)->getViewCount();
// returns the cached result
$viewCountAgain = memoize($user)->getViewCount();
As you can tell, the function takes a target object as the first argument and returns a new class instance on which you can call the methods of the target object.
Essentially, the function creates a new class instance and leverages the __call()
magic method to call the method on the target object. It then caches the result of the method call and returns the cached result if the method is called again with the same arguments.
It uses WeakMap
to cache the result of the method call. This is because WeakMap
doesn’t hold a reference to the key. So, when the key is no longer referenced, it will be removed from the map and the memory will be freed.
Pretty intriguing little function, isn’t it?
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.