PHP code example of antevenio / memoize

1. Go to this page and download the library: Download antevenio/memoize library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

antevenio / memoize example snippets



Antevenio\Memoize\Memoizable;
use Antevenio\Memoize\Memoize;
use Antevenio\Memoize\Cache;

class Toolbox
{
    public function multiply($argument)
    {
        echo "Called with {$argument}\n";

        return $argument * 2;
    }
    
    public function throwException($argument)
    {
        echo "Called with {$argument}\n";

        throw new \Exception($argument);
    }
}

$toolbox = new Toolbox();
$memoize = new Memoize((new Cache())->setEntryLimit(100));

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'multiply'], [10]))->withTtl(5)
    );
    echo "Result: $result\n";
    sleep(1);
}

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'multiply'], [$i % 2]))->withTtl(5)
    );
    echo "Result: $result\n";
    sleep(1);
}

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'multiply'], [$i]))->withTtl(5)->withCustomIndex('myFixedIndex')
    );
    echo "Result: $result\n";
    sleep(1);
}

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'throwException'], ['foo']))->withTtl(5)
    );
    echo "Result: $result\n";
    sleep(1);
}