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.