PHP code example of traderinteractive / memoize

1. Go to this page and download the library: Download traderinteractive/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/ */

    

traderinteractive / memoize example snippets


interface Memoize
{
    /**
     * Gets the value stored in the cache or uses the passed function to
     * compute the value and save to cache.
     *
     * @param string $key The key to fetch
     * @param callable $compute A function to run if the value was not cached
     *     that will return the result.
     * @param int $cacheTime The number of seconds to cache the response for,
     *     or null to not expire it ever.
     * @return mixed The data requested, optionally pulled from cache
     */
    public function memoizeCallable($key, $compute, $cacheTime = null);
}

$getUser = function($database, $userId) {
  $query = $database->select('*')->from('user')->where(['id' => $userId]);
  return $query->fetchOne();
};

$getLoggedInUser = function() use($database, $loggedInUserId, $getUser) {
    return $getUser($database, $loggedInUserId);
};

$memoize->memoizeCallable("getUser-{$loggedInUserId}", $getLoggedInUser);

$getUserLocator = function($database, $userId) use($getUser) {
    return function() use($database, $userId, $getUser) {
        return $getUser($database, $userId);
    };
};

$getLoggedInUser = $getUserLocator($database, $loggedInUserId);
$memoize->memoizeCallable("getUser-{$loggedInUserId}", $getLoggedInUser);

$predis = new \Predis\Client($redisUrl);
$memoize = new \TraderInteractive\Memoize\Predis($predis);

$compute = function() {
    // Perform some long operation that you want to memoize
};

// Cache he results of $compute for 1 hour.
$result = $memoize->memoizeCallable('myLongOperation', $compute, 3600);

$memoize = new \TraderInteractive\Memoize\Memory();

$compute = function() {
    // Perform some long operation that you want to memoize
};

$result = $memoize->memoizeCallable('myLongOperation', $compute);

$memoize = new \TraderInteractive\Memoize\None();

$compute = function() {
    // Perform some long operation that you want to memoize
};

// This will never actually memoize the results - they will be recomputed every
// time.
$result = $memoize->memoizeCallable('myLongOperation', $compute);