How to create a simple memoization helper in PHP

Parvej Ahammad
2 min readMay 23, 2022

First of all, what is memoization? From Wikipedia

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

Whenever we call a function with the same arguments, it will return the cached results instead of re-calculating.
In my case, I want to keep things simple instead of checking function arguments every time. I will cache the result against a key passed to the memoization helper. Here goes a simple implementation of it

<?php
namespace App\Helpers\Core\Traits;
trait Memoization
{
protected static $memoized = [];
public function memoize(
string $key,
\Closure $callback
) {
if (!isset(static::$memoized[$key])) {
return static::$memoized[$key] = $callback();
}
return static::$memoized[$key];
}
}

The code itself is self-explanatory. First, we declared a static type property with an empty array as a value to store the cached result of the executed function. In our memoize function, we check if the key exists in our $memoized static property. If it doesn’t, we run the callback function, store it to the $momoized property in the passed key, and return the value. If it does exist, then we return the already cached result.

Usage:

$this->memoize('a_static_key_to_store_value', function () {
//Do your things
});

So the question arises: how will you handle if the function’s arguments change? Instead of using a static key for caching the function result, the answer is simple: use a unique key based on function arguments.
For example, I want to get user-defined settings from the database, which will be used in several places. So instead of passing only `settings` as a key, pass `”settings-$user_id”`

$this->memoize("settings-$user_id", function () use($user_id) {
//Get the value from database using $user_id
//Parse it the way you need it
});

--

--