PHPackages                             tomloprod/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. tomloprod/memoize

ActiveLibrary[Caching](/categories/caching)

tomloprod/memoize
=================

Memoize is a lightweight PHP library designed to handle memoization with ease.

v2.3.0(9mo ago)4114.7k↑558%2MITPHPPHP ^8.2.0CI passing

Since Jul 25Pushed 9mo agoCompare

[ Source](https://github.com/tomloprod/memoize)[ Packagist](https://packagist.org/packages/tomloprod/memoize)[ Fund](https://www.paypal.com/paypalme/tomloprod)[ RSS](/packages/tomloprod-memoize/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (5)Dependencies (4)Versions (6)Used By (0)

🧠 Memoize - PHP Memoization Library
===================================

[](#-memoize---php-memoization-library)

**High-performance memoization and function caching library for PHP**

 [![GitHub Workflow Status (master)](https://github.com/tomloprod/memoize/actions/workflows/tests.yml/badge.svg)](https://github.com/tomloprod/memoize/actions) [![Total Downloads](https://camo.githubusercontent.com/95b573d3bd10287f5076676e65f11412d796c8ed7d0683479ea0dc33a4b25a7f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f6d6c6f70726f642f6d656d6f697a65)](https://packagist.org/packages/tomloprod/memoize) [![Latest Version](https://camo.githubusercontent.com/7bb1e4e8ba003ada53f8f5d01ecab66a809a6f7f1848b1fbc5e3ff7a1006aae9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f6d6c6f70726f642f6d656d6f697a65)](https://packagist.org/packages/tomloprod/memoize) [![License](https://camo.githubusercontent.com/98879c55def50cc8d3e578135c319831c61275f44dfdf1d7ba3e32e81e2a3040/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f6d6c6f70726f642f6d656d6f697a65)](https://packagist.org/packages/tomloprod/memoize)

---

🎯 **About Memoize**
-------------------

[](#-about-memoize)

**Memoize** is a lightweight PHP library designed to implement memoization and function caching techniques with ease.

Transform expensive function calls into lightning-fast cache lookups with zero configuration.

✨ **Features**
--------------

[](#-features)

🔑 **Key-based Memoization**
Cache function results with custom keys

⚡ **Single Execution**
Functions run only once, results cached forever

🏷️ **Namespaces**
Organize cache by classes or contexts

🧠 **LRU Cache**
Automatic memory management with size limits

📊 **Cache Analytics**
Built-in statistics and monitoring

🏃 **Runtime Flags**
Dynamic behavior control during execution

🔄 **Enable/Disable**
Temporarily disable memoization when needed

🚀 **Quick Start - PHP Memoization**
-----------------------------------

[](#-quick-start---php-memoization)

### Installation

[](#installation)

```
composer require tomloprod/memoize
```

### Basic Usage

[](#basic-usage)

#### 🏷️ **Namespace Organization**

[](#️-namespace-organization)

If you want to get the most out of the package and better organize your memoization, we recommend using namespaces.

When using namespaces, if you use a `$key` with a null value, the callback won’t be executed (*especially useful in certain cases*).

```
// Organize cache by context
$userSettings = memoize()
    ->for(UserSettings::class)
    ->memo($userId, fn() => UserSettings::where('user_id', $userId)->first());

$productCache = memoize()
    ->for(Product::class)
    ->memo($productId, fn() => Product::with('variants')->find($productId));
```

#### 🔑 **Key-based Memoization**

[](#-key-based-memoization)

You can also not use namespaces and just memoize keys.

```
// Expensive API call cached by key
$weather = memoize()->memo(
    'weather_london',
    fn() => Http::get('api.weather.com/london')->json()
);

// Database query with dynamic key
$user = memoize()->memo(
    "user_{$id}",
    fn() => User::with('profile', 'orders')->find($id)
);
```

#### ⚡ **Single Execution Functions**

[](#-single-execution-functions)

```
// Initialize expensive resources only once
$services = memoize()->once(fn() => [
    'redis' => new Redis(),
    'elasticsearch' => new Client(),
    'logger' => new Logger(),
]);

$redis = $services()['redis']; // Initialized once
$same = $services()['redis'];  // Same instance
```

#### 🧠 **Memory Management**

[](#-memory-management)

The library uses an **LRU (Least Recently Used)** algorithm to automatically manage memory and prevent unlimited cache growth.

**How does LRU work?**

- Maintains a record of the access order for cache entries
- When the maximum limit (`maxSize`) is reached, automatically removes the **least recently used** entry
- Every time you access an entry (read or write), it moves to the front of the queue
- Older entries remain at the end and are candidates for removal

This ensures that the most relevant and frequently used data remains in memory, while obsolete data is automatically removed.

```
// Set LRU cache limit (by default, there is no max size)
memoize()->setMaxSize(1000);

// Cache statistics
$stats = memoize()->getStats();
// ['size' => 150, 'maxSize' => 1000, 'head' => [...], 'tail' => [...]]

// Clear specific or all cache
memoize()->forget('user_123');
memoize()->for('App\\Model\\User')->forget('123');

// Or clear all cache
memoize()->flush();
```

#### 🔄 **Enable/Disable Memoization**

[](#-enabledisable-memoization)

You can temporarily disable memoization to bypass caching when needed. When disabled, callbacks are executed every time without storing results in cache.

```
// Disable memoization
memoize()->disable();

// Now all memo() calls will execute callbacks without caching
$result1 = memoize()->memo('key', fn() => expensiveOperation()); // Executes
$result2 = memoize()->memo('key', fn() => expensiveOperation()); // Executes again

// Re-enable memoization
memoize()->enable();

// Now caching works normally again
$result3 = memoize()->memo('key', fn() => expensiveOperation()); // Executes and caches
$result4 = memoize()->memo('key', fn() => expensiveOperation()); // Returns cached value

// Check current state
if (memoize()->isEnabled()) {
    // Memoization is active
}
```

**Use cases:**

- Debugging: Temporarily disable caching to see fresh data
- Testing: Ensure callbacks execute every time during tests
- Conditional behavior: Disable caching based on environment or conditions

#### 🏃 **Runtime Flags**

[](#-runtime-flags)

Control memoization behavior dynamically during execution with runtime flags. These flags exist only in memory and reset between requests/processes.

**How do runtime flags work?**

- Flags are stored in memory during the current execution
- They allow conditional behavior without external configuration
- Perfect for debug modes, logging control, and dynamic optimizations
- Automatically cleared when the process ends

```
// Skip cache during testing
memoize()->enableFlag('bypass_cache');

$userData = memoize()->memo("user_{$id}", function() use ($id) {
    if (memoize()->hasFlag('bypass_cache')) {
        return User::fresh()->find($id); // Always fetch from DB in tests
    }
    return User::find($id);
});

// Feature toggles without external dependencies
memoize()->enableFlag('new_algorithm');

$result = memoize()->memo($cacheKey, function() {
    if (memoize()->hasFlag('new_algorithm')) {
        return $this->calculateWithNewAlgorithm();
    }
    return $this->calculateWithOldAlgorithm();
});

// Development vs Production behavior
if (app()->environment('local') && memoize()->hasFlag('dev_mode')) {
    memoize()->enableFlags(['verbose_logging', 'bypass_cache']);
}

// Model boot method with conditional service calls
class Product extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::updated(function ($product) {
            // Only call external stock service if flag is not set
            if (! memoize()->hasFlag('disableStockService')) {
                app(StockService::class)->updateInventory($product);
            }
        });
    }
}
```

**Runtime Flag Methods:**

**Method****Description****enableFlag(string $flag)**

Enable a specific runtime flag**disableFlag(string $flag)**

Disable a specific runtime flag**toggleFlag(string $flag)**

Toggle flag state (enabled/disabled)**hasFlag(string $flag): bool**

Check if a specific flag is enabled**enableFlags(array $flags)**

Enable multiple flags at once**disableFlags(array $flags)**

Disable multiple flags at once**hasAnyFlag(array $flags): bool**

Check if at least one flag is enabled**hasAllFlags(array $flags): bool**

Check if all specified flags are enabled**getFlags(): array**

Get all currently enabled flags**clearFlags()**

Clear all enabled flags💡 **Advanced Examples**
-----------------------

[](#-advanced-examples)

### 🏃‍♂️ **Performance Optimization**

[](#‍️-performance-optimization)

```
// Fibonacci with memoization - O(n) instead of O(2^n)
function fibonacci(int $n): int {
    return memoize()->memo(
        "fib_{$n}",
        fn() => $n memo(
    "sales_report_{$month}",
    fn() => Order::whereMonth('created_at', $month)
        ->with('items.product')
        ->get()
        ->groupBy('status')
        ->map(fn($orders) => $orders->sum('total'))
);
```

📖 **API Reference**
-------------------

[](#-api-reference)

### Core Methods

[](#core-methods)

**Method****Description****memo(string|int|float|null $key, callable $callback)**

**Key-based memoization** - Execute callback and cache result by key. Returns cached value on subsequent calls.

**once(callable $callback)**

**Single execution** - Returns a wrapper function that executes the callback only once, caching the result forever.

**for(string $class)**

**Namespace organization** - Set namespace to organize cache by class/context. Automatically cleared after use.

### Cache Management

[](#cache-management)

**Method****Description****has(string|int|float $key): bool**

Check if a key exists in cache**forget(string|int|float $key): bool**

Remove specific key from cache**flush(): void**

Clear all cached values**setMaxSize(?int $maxSize): void**

Set maximum entries (LRU eviction)**getStats(): array**

Get detailed cache statistics**disable(): void**

Disable memoization (callbacks execute without caching)**enable(): void**

Enable memoization (default state)**isEnabled(): bool**

Check if memoization is currently enabled⚙️ **Requirements &amp; Installation**
--------------------------------------

[](#️-requirements--installation)

- **PHP 8.2+**
- **Composer**

```
composer require tomloprod/memoize
```

**🧑‍🤝‍🧑 Contributing**
----------------------

[](#‍‍-contributing)

Contributions are welcome, and are accepted via pull requests. Please [review these guidelines](./CONTRIBUTING.md) before submitting any pull requests.

---

**Memoize** was created by **[Tomás López](https://twitter.com/tomloprod)** and open-sourced under the **[MIT license](https://opensource.org/licenses/MIT)**.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance57

Moderate activity, may be stable

Popularity37

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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 ~26 days

Total

5

Last Release

282d ago

Major Versions

v1.0.0 → v2.0.02025-09-21

### Community

Maintainers

![](https://www.gravatar.com/avatar/1c9df012919bdcf3f17fad0e3a84ec77641f1f9671f85cb9c4377242ba09dde8?d=identicon)[tomloprod](/maintainers/tomloprod)

---

Top Contributors

[![tomloprod](https://avatars.githubusercontent.com/u/7898894?v=4)](https://github.com/tomloprod "tomloprod (12 commits)")

---

Tags

cacheflagsfluent-apimemoizeperformance-optimizationphputilitymemoization

###  Code Quality

TestsPest

Static AnalysisRector

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[spatie/once

A magic memoization function

1.4k30.2M111](/packages/spatie-once)[traderinteractive/memoize

A library for memoizing repeated function calls.

43141.6k](/packages/traderinteractive-memoize)[iazaran/smart-cache

Smart Cache is a caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.

21114.2k](/packages/iazaran-smart-cache)[ichhabrecht/intcache

Turn uncachable page objects into cacheable links

193.9k](/packages/ichhabrecht-intcache)

PHPackages © 2026

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