PHPackages                             traderinteractive/memoize - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. traderinteractive/memoize

ActiveLibrary[Caching](/categories/caching)

traderinteractive/memoize
=========================

A library for memoizing repeated function calls.

v3.0.0(1y ago)43125.7k—8.6%12MITPHPPHP ^7.0 || ^8.0CI passing

Since Mar 13Pushed 1y ago23 watchersCompare

[ Source](https://github.com/traderinteractive/memoize-php)[ Packagist](https://packagist.org/packages/traderinteractive/memoize)[ RSS](/packages/traderinteractive-memoize/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (12)Used By (0)

Memoize
=======

[](#memoize)

A PHP library for memoizing repeated function calls.

[![Latest Stable Version](https://camo.githubusercontent.com/c269e6b7b7b3e09d61b127d6e37ab0a6cc656832606693c2401f5e8886a126e0/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f747261646572696e7465726163746976652f6d656d6f697a652e7376673f7374796c653d666c6174)](https://packagist.org/packages/traderinteractive/memoize)[![Total Downloads](https://camo.githubusercontent.com/97f95f408684168c3204d8b677fd1895031fce183365783c809c4c5af6ee3365/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f747261646572696e7465726163746976652f6d656d6f697a652e7376673f7374796c653d666c6174)](https://packagist.org/packages/traderinteractive/memoize)[![License](https://camo.githubusercontent.com/c417f4a287589c104ca51ad266fa37b0878a22d8ed898fcfe0860daa5c6b99a4/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f747261646572696e7465726163746976652f6d656d6f697a652e7376673f7374796c653d666c6174)](https://packagist.org/packages/traderinteractive/memoize)

Requirements
------------

[](#requirements)

This library requires PHP 7.0, or newer.

Installation
------------

[](#installation)

This package uses [composer](https://getcomposer.org) so you can just add `traderinteractive/memoize` as a dependency to your `composer.json` file.

Memoization
-----------

[](#memoization)

[Memoization](http://en.wikipedia.org/wiki/Memoization) is a way of optimizing a function that is called repeatedly by caching the results of a function call.

Memoization Providers
---------------------

[](#memoization-providers)

This library includes several built-in providers for memoization. Each one implements the `\TraderInteractive\Memoize\Memoize` interface:

```
interface Memoize
{
    /**
     * Gets the value stored in the cache or uses the passed function to
     * compute the value and save to cache.
     *
     * @param string $key The key to fetch
     * @param callable $compute A function to run if the value was not cached
     *     that will return the result.
     * @param int $cacheTime The number of seconds to cache the response for,
     *     or null to not expire it ever.
     * @return mixed The data requested, optionally pulled from cache
     */
    public function memoizeCallable($key, $compute, $cacheTime = null);
}
```

The `$compute` callable must not take any parameters - if you need parameters, consider wrapping your function in a closure that pulls the required parameters into scope. For example, given the function:

```
$getUser = function($database, $userId) {
  $query = $database->select('*')->from('user')->where(['id' => $userId]);
  return $query->fetchOne();
};
```

You could wrap this in a closure like so:

```
$getLoggedInUser = function() use($database, $loggedInUserId, $getUser) {
    return $getUser($database, $loggedInUserId);
};

$memoize->memoizeCallable("getUser-{$loggedInUserId}", $getLoggedInUser);
```

Alternatively, you could invert this and return the closure instead, like so:

```
$getUserLocator = function($database, $userId) use($getUser) {
    return function() use($database, $userId, $getUser) {
        return $getUser($database, $userId);
    };
};

$getLoggedInUser = $getUserLocator($database, $loggedInUserId);
$memoize->memoizeCallable("getUser-{$loggedInUserId}", $getLoggedInUser);
```

Future versions of this library may add support for parameters, as it can be a common usecase (especially when it comes to recursive functions.

Also worth noting, is that you need to make sure you define your cache keys uniquely for anything using the memoizer.

### Predis

[](#predis)

The predis provider uses the [predis](https://github.com/nrk/predis) library to cache the results in Redis. It supports the `$cacheTime` parameter so that results can be recomputed after the time expires.

This memoizer can be used in a way that makes it persistent between processes rather than only caching computation for the current process.

#### Example

[](#example)

```
$predis = new \Predis\Client($redisUrl);
$memoize = new \TraderInteractive\Memoize\Predis($predis);

$compute = function() {
    // Perform some long operation that you want to memoize
};

// Cache he results of $compute for 1 hour.
$result = $memoize->memoizeCallable('myLongOperation', $compute, 3600);
```

### Memcache

[](#memcache)

The memcache provider uses the [memcache](https://www.php.net/manual/en/book.memcache.php) library to cache the results in Memcache. It supports the `$cacheTime` parameter so that results can be recomputed after the time expires.

This memoizer can be used in a way that makes it persistent between processes rather than only caching computation for the current process.

#### Example

[](#example-1)

```
$memcache = new Memcache;
$memcacheInstance = $memcache->connect('127.0.0.1', 11211);
$memoize = new \TraderInteractive\Memoize\Memcache($memcacheInstance);

$compute = function() {
    // Perform some long operation that you want to memoize
};

// Cache he results of $compute for 1 hour.
$result = $memoize->memoizeCallable('myLongOperation', $compute, 3600);
```

### Memory

[](#memory)

This is a standard in-memory memoizer. It does not support `$cacheTime` at the moment and only keeps the results around as long as the memoizer is in memory.

#### Example

[](#example-2)

```
$memoize = new \TraderInteractive\Memoize\Memory();

$compute = function() {
    // Perform some long operation that you want to memoize
};

$result = $memoize->memoizeCallable('myLongOperation', $compute);
```

### None

[](#none)

This memoizer does not actually memoize anything - it always calls the `$compute` function. It is useful for testing and can also be used when you disable memoization for debugging, etc. because you can swap your real memoizer out for this one and everything will still work.

#### Example

[](#example-3)

```
$memoize = new \TraderInteractive\Memoize\None();

$compute = function() {
    // Perform some long operation that you want to memoize
};

// This will never actually memoize the results - they will be recomputed every
// time.
$result = $memoize->memoizeCallable('myLongOperation', $compute);
```

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance41

Moderate activity, may be stable

Popularity46

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~422 days

Recently: every ~589 days

Total

10

Last Release

643d ago

Major Versions

v0.2.0 → v1.0.02018-03-01

v1.0.1 → v2.0.02022-09-15

v2.0.1 → v3.0.02024-08-13

PHP version history (5 changes)v0.1.0PHP &gt;=5.3.2

v0.1.3PHP ~5.4

v0.2.0PHP ~5.4 || ~7.0

v1.0.0PHP ^7.0

v2.0.0PHP ^7.0 || ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/29952359?v=4)[Trader Interactive](/maintainers/traderinteractive)[@traderinteractive](https://github.com/traderinteractive)

---

Top Contributors

[![chrisryan](https://avatars.githubusercontent.com/u/704326?v=4)](https://github.com/chrisryan "chrisryan (27 commits)")[![s-sathish](https://avatars.githubusercontent.com/u/41979412?v=4)](https://github.com/s-sathish "s-sathish (13 commits)")[![nubs](https://avatars.githubusercontent.com/u/57673?v=4)](https://github.com/nubs "nubs (9 commits)")[![chadicus](https://avatars.githubusercontent.com/u/1182337?v=4)](https://github.com/chadicus "chadicus (4 commits)")[![raybot](https://avatars.githubusercontent.com/u/1583780?v=4)](https://github.com/raybot "raybot (3 commits)")[![guywithnose](https://avatars.githubusercontent.com/u/1059169?v=4)](https://github.com/guywithnose "guywithnose (2 commits)")[![williamhuntjr](https://avatars.githubusercontent.com/u/110130384?v=4)](https://github.com/williamhuntjr "williamhuntjr (2 commits)")

---

Tags

cachepredisoptimizationmemoization

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/traderinteractive-memoize/health.svg)

```
[![Health](https://phpackages.com/badges/traderinteractive-memoize/health.svg)](https://phpackages.com/packages/traderinteractive-memoize)
```

###  Alternatives

[psr/simple-cache

Common interfaces for simple caching

8.1k727.3M2.1k](/packages/psr-simple-cache)[psr/cache

Common interface for caching libraries

5.2k686.9M1.3k](/packages/psr-cache)[predis/predis

A flexible and feature-complete Redis/Valkey client for PHP.

7.8k305.7M2.4k](/packages/predis-predis)[spatie/once

A magic memoization function

1.4k29.1M79](/packages/spatie-once)[cache/predis-adapter

A PSR-6 cache implementation using Redis (Predis). This implementation supports tags

272.6M13](/packages/cache-predis-adapter)[contributte/redis

Redis client integration into Nette framework

181.6M2](/packages/contributte-redis)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
