4,000 emails/month for free | Mailtrap sends real emails now!

Memoization and Function Caching with this PHP Package

Last updated on by

Memoization and Function Caching with this PHP Package image

Memoize is a lightweight PHP library that simplifies function caching and memoization. It can help boost your application's performance by storing the results of costly function calls, so repeated calls with the same arguments return instantly without reprocessing:

// Using the helper function
$result1 = memoize()->memo('expensive_calc', function () {
sleep(2); // Simulates expensive operation
return 42 * 1.5 + rand(1, 100);
});
 
// Second call with same key: returns cached result (fast)
$result2 = memoize()->memo('expensive_calc', function () {
sleep(2); // This won't execute
return 99999; // This value is ignored, cached value is returned
});
 
// $result1 === $result2 (same cached value)
 
// Different key: executes the function again
$result3 = memoize()->memo('another_calc', function () {
return 'different calculation';
});

This memoization package is handy for performance optimization, such as expensive database queries, API calls, configuration loading, file processing, and more:

$getUserData = function ($userId) {
// Expensive database query or API call
return database()->query("SELECT * FROM users WHERE id = ?", [$userId]);
};
 
// Cache user data by ID
$user = memoize()->memo("user_$userId", $getUserData);
$sameUser = memoize()->memo("user_$userId", $getUserData); // From cache

Main Features

  • Cache results of expensive functions - cache expensive functions to avoid repeated calculations
  • Key-based memoization - Cache function results using custom keys for efficient retrieval
  • Single execution functions - Execute functions only once and reuse the result in subsequent calls
  • Simple and intuitive API - Facade and helper function for easy integration
  • Cache management - Methods to check, remove, and clear cached values

You can get started with this package on GitHub: tomloprod/memoize

Related: If you're using the Laravel framework, check out the once() helper and Memoized Cache Driver. Spatie also has the spatie/once package, which is a magic memoization function you can use in your PHP projects.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Curotec

Curotec helps software teams hire the best Laravel developers in Latin America. Click for rates and to learn more about how it works.

Visit Curotec
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support image

Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support

Read article
Statamic 6 Beta Now Available image

Statamic 6 Beta Now Available

Read article
Everything new in Livewire 4 image

Everything new in Livewire 4

Read article
Cache Without Overlapping in Laravel 12.47.0 image

Cache Without Overlapping in Laravel 12.47.0

Read article
Going Real-Time with Reverb - Laravel In Practice EP17 image

Going Real-Time with Reverb - Laravel In Practice EP17

Read article
The Neuron AI Framework for PHP and Laravel image

The Neuron AI Framework for PHP and Laravel

Read article