2017 © Pedro Peláez

library memoize

Memoize functions with a trait or by extending an object.



Memoize functions with a trait or by extending an object.

  • Sunday, January 28, 2018
  • by drupol
  • Repository
  • 2 Watchers
  • 2 Stars
  • 147 Installations
  • PHP
  • 1 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 9 Versions
  • 0 % Grown


Latest Stable Version ![GitHub stars][github stars] Total Downloads ![GitHub Workflow Status][github workflow status] ![Scrutinizer code quality][code quality] Type Coverage ![Code Coverage][code coverage] ![License][license] ![Donate!][donate paypal], (*1)

PHP Memoize


Memoizer class for callable., (*2)

From wikipedia:, (*3)

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again., (*4)

This library help you to memoize callable or closures., (*5)

It can use any type of Cache backend system, as long as it implements the PSR-6 cache interface., (*6)

If you use the symfony/cache package, you will have a bunch of cache backends available such as Redis, MemCache, Filesystem, ArrayCache,..., (*7)


  • Provides a Memoizer class,
  • Allows you to set a custom cache,


With composer:, (*8)

composer require loophp/memoize, (*9)




namespace App;

include 'vendor/autoload.php';

use Closure;
use loophp\memoize\Memoizer;

$fibonacci = static function (int $number) use (&$fibonacci): int {
    return (1 >= $number) ?
        $number :
        $fibonacci($number - 1) + $fibonacci($number - 2);

$fibonacci = Memoizer::fromClosure($fibonacci);

function bench(Closure $closure, ...$arguments): array
    $start = microtime(true);

    return [
        microtime(true) - $start,

var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 50)));
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 50)));

Code style, code quality, tests and benchmarks

The code style is following PSR-12 plus a set of custom rules, the package drupol/php-conventions is responsible for this., (*10)

Every time changes are introduced into the library, Github CI run the tests and the benchmarks., (*11)

The library has tests written with PHPSpec. Feel free to check them out in the spec directory. Run composer phpspec to trigger the tests., (*12)

PHPInfection is used to ensure that your code is properly tested, run composer infection to test your code., (*13)


See the file CONTRIBUTING.md but feel free to contribute to this library by sending Github pull requests., (*14)

The Versions