PHP Classes

How to Implement a PHP Memoize Function to Store and Retrieve Cache Values in Arrays Using the Package Memoize: Store and retrieve cache values in arrays

Recommend this page to a friend!
  Info   Documentation   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-09-22 (Less than 1 hour ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
memoize 1.0.1Custom (specified...8Cache, PHP 8
Description 

Author

This package can store and retrieve cache values in arrays.

It provides a manager class that can call a cache class to perform several operations to store and retrieve cached values.

Currently, it can:

- Store a value returned by a callback function and associate with a given key in a private array if the cached value was not yet already stored, or return the stored value associated with a given key.

- Discard a cached value associated with a given key

- Discard all cached values

- Check if there is a value associated to a given key

Picture of tomloprod
  Performance   Level  
Name: tomloprod <contact>
Classes: 4 packages by
Country: Spain Spain
Age: ???
All time rank: 4113112 in Spain Spain
Week rank: 195 Up5 in Spain Spain Up

Instructions

Please read this document, store and retrieve cached values using callback functions, as well as other features of the memoize() class.

Documentation

<div align="center">

? Memoize

High-performance memoization library for PHP

<p align="center">

<p align="center">
    <a href="https://github.com/tomloprod/memoize/actions"><img alt="GitHub Workflow Status (master)" src="https://github.com/tomloprod/memoize/actions/workflows/tests.yml/badge.svg"></a>
    <a href="https://packagist.org/packages/tomloprod/memoize"><img alt="Total Downloads" src="https://img.shields.io/packagist/dt/tomloprod/memoize"></a>
    <a href="https://packagist.org/packages/tomloprod/memoize"><img alt="Latest Version" src="https://img.shields.io/packagist/v/tomloprod/memoize"></a>
    <a href="https://packagist.org/packages/tomloprod/memoize"><img alt="License" src="https://img.shields.io/packagist/l/tomloprod/memoize"></a>
</p>

</p>

</div>

? 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

<table> <tr> <td width="50%">

? 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

</td> <td width="50%">

? LRU Cache Automatic memory management with size limits

? Simple API Intuitive facade and helper functions

? Cache Analytics Built-in statistics and monitoring

</td> </tr> </table>

? Quick Start

Installation

composer require tomloprod/memoize

Basic Usage

?? 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

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

// 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

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();

? Advanced Examples

???? Performance Optimization

// Fibonacci with memoization - O(n) instead of O(2^n)
function fibonacci(int $n): int {
    return memoize()->memo(
        "fib_{$n}", 
        fn() => $n <= 1 ? $n : fibonacci($n - 1) + fibonacci($n - 2)
    );
}

// Complex data aggregation
$salesReport = memoize()->memo(
    "sales_report_{$month}", 
    fn() => Order::whereMonth('created_at', $month)
        ->with('items.product')
        ->get()
        ->groupBy('status')
        ->map(fn($orders) => $orders->sum('total'))
);

? API Reference

Core Methods

<table> <tr><td width="30%"><strong>Method</strong></td><td><strong>Description</strong></td></tr> <tr><td>

memo(?string $key, callable $callback)

</td><td>

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

</td></tr> <tr><td>

once(callable $callback)

</td><td>

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

</td></tr> <tr><td>

for(string $class)

</td><td>

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

</td></tr> </table>

Cache Management

<table> <tr><td width="30%"><strong>Method</strong></td><td><strong>Description</strong></td></tr> <tr><td>

has(string $key): bool

</td><td>Check if a key exists in cache</td></tr> <tr><td>

forget(string $key): bool

</td><td>Remove specific key from cache</td></tr> <tr><td>

flush(): void

</td><td>Clear all cached values</td></tr> <tr><td>

setMaxSize(?int $maxSize): void

</td><td>Set maximum entries (LRU eviction)</td></tr> <tr><td>

getStats(): array

</td><td>Get detailed cache statistics</td></tr> </table>

?? Requirements & Installation

  • PHP 8.2+
  • Composer
composer require tomloprod/memoize

????? Contributing

Contributions are welcome, and are accepted via pull requests. Please review these guidelines before submitting any pull requests.

Memoize was created by Tomás López and open-sourced under the MIT license.


  Files folder image Files (21)  
File Role Description
Files folder image.github (1 file, 1 directory)
Files folder imagesrc (2 directories)
Files folder imagetests (1 file, 2 directories)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file LICENSE.md Lic. License text
Accessible without login Plain text file phpstan.neon.dist Data Auxiliary data
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file pint.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Accessible without login Plain text file rector.php Example Example script

  Files folder image Files (21)  /  .github  
File Role Description
Files folder imageworkflows (2 files)
  Accessible without login Plain text file FUNDING.yml Data Auxiliary data

  Files folder image Files (21)  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file formats.yml Data Auxiliary data
  Accessible without login Plain text file tests.yml Data Auxiliary data

  Files folder image Files (21)  /  src  
File Role Description
Files folder imageServices (2 files)
Files folder imageSupport (1 file, 1 directory)

  Files folder image Files (21)  /  src  /  Services  
File Role Description
  Plain text file MemoEntry.php Class Class source
  Plain text file MemoizeManager.php Class Class source

  Files folder image Files (21)  /  src  /  Support  
File Role Description
Files folder imageFacades (1 file)
  Accessible without login Plain text file MemoizeAlias.php Aux. Configuration script

  Files folder image Files (21)  /  src  /  Support  /  Facades  
File Role Description
  Plain text file Memoize.php Class Class source

  Files folder image Files (21)  /  tests  
File Role Description
Files folder imageServices (2 files)
Files folder imageSupport (1 file, 1 directory)
  Accessible without login Plain text file ArchTest.php Example Example script

  Files folder image Files (21)  /  tests  /  Services  
File Role Description
  Accessible without login Plain text file MemoEntryTest.php Example Example script
  Plain text file MemoizeManagerTest.php Class Class source

  Files folder image Files (21)  /  tests  /  Support  
File Role Description
Files folder imageFacades (1 file)
  Plain text file MemoizeAliasTest.php Class Class source

  Files folder image Files (21)  /  tests  /  Support  /  Facades  
File Role Description
  Accessible without login Plain text file MemoizeTest.php Example Example script

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0