Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy 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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
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
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
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Lucky Media logo

Lucky Media

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

Lucky Media
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
PhpStorm logo

PhpStorm

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

PhpStorm
Shift logo

Shift

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

Shift
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
Tinkerwell logo

Tinkerwell

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

Tinkerwell

The latest

View all →
Laravel Schema Sentinel: Detect and Fix Database Schema Drift image

Laravel Schema Sentinel: Detect and Fix Database Schema Drift

Read article
Laravel Web Push Notifications image

Laravel Web Push Notifications

Read article
RedBerry to Host Georgia's First Laravel Meetup in Tbilisi image

RedBerry to Host Georgia's First Laravel Meetup in Tbilisi

Read article
Interruptible Jobs in Laravel 13.7.0 image

Interruptible Jobs in Laravel 13.7.0

Read article
A Free Shift to Check If Your App is Ready for Laravel Cloud image

A Free Shift to Check If Your App is Ready for Laravel Cloud

Read article
Laravel Idempotency: HTTP Idempotency Middleware for Laravel image

Laravel Idempotency: HTTP Idempotency Middleware for Laravel

Read article