PHP code example of solodkiy / memorize

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

    

solodkiy / memorize example snippets


class Singleton
{
    /**
     * @var Singleton
     */
    private static $instance;
    
    private function __construct()
    {
        // private
    }

    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

class Singleton
{
    private function __construct()
    {
        // private
    }

    public static function getInstance()
    {
        return memorize(function() {
            return new Singleton();
        });
    }
}

function factorial($number)
{
    return memorize(function () use ($number) {
        if ($number <= 0) {
            throw new \InvalidArgumentException('Number must be natural');
        }
        return ($number == 1)
            ? 1
            : $number * factorial($number - 1);
    });
}


class TableGateway
{
    /**
     * @var array
     */ 
    private $cacheStatistic = [];
    
    public function getA($accountId)
    {
        return $this->calculateStatistic($accountId)['a'];
    }
    
    public function getB($accountId)
    {
        return $this->calculateStatistic($accountId)['b'];
    }
    
    private function calculateStatistic($accountId)
    {
        if (!isset($this->cacheStatistic[$accountId])) {
            $sql = 'SELECT AVG(price) AS a ...';
            $result = $this->db->getRows($sql, [$accountId]);
            $this->cacheStatistic[$accountId] = $result;
        }
        return $this->cacheStatistic[$accountId];
    }
}

class TableGateway
{
    public function getA($accountId)
    {
        return $this->calculateStatistic($accountId)['a'];
    }
    
    public function getB($accountId)
    {
        return $this->calculateStatistic($accountId)['b'];
    }
    
    private function calculateStatistic($accountId)
    {
        return memorize(function () use ($accountId) {
            $sql = 'SELECT AVG(price) AS a ...';
            return $this->db->getRows($sql, [$accountId]);
        });
    }
}