PHP code example of laracraft-tech / memoize

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

    

laracraft-tech / memoize example snippets


use LaracraftTech\Memoize\HasMemoization;

$myClass = new class()
{    
    use HasMemoization;

    public function getNumber(): int
    {
        return $this->memoize(function () {
            return rand(1, 10000);
        });
    }
};

$myClass = new class()
{
    use HasMemoization;
    
    public function getNumberForLetter($letter)
    {
        return $this->memoize(function () use ($letter) {
            return $letter . rand(1, 10000000);
        });
    }
}

use LaracraftTech\Memoize\HasMemoization;

$myClass = new class()
{
    use HasMemoization;
    
    public function processSomethingHeavy1($someModel)
    {
        // ...
        
        $relation = $this->memoize(function () use ($someModel) {
            return Foo::find($someModel->foo_relation_id);
        }, $someModel->foo_relation_id); // <--- custom once per combination key
        
        // ...
    }
    
    // you could also do something like this (maybe more convinient)
    public function processSomethingHeavy2($someModel)
    {
        // ...
        
        $foo_relation_id = $someModel->foo_relation_id;
        $relation = $this->memoize(function () use ($foo_relation_id) {
            return Foo::find($foo_relation_id);
        });
        
        // ...
    }
    
    // this would work but will lose performance on each new $someModel even foo_relation_id would be the same
    public function processSomethingHeavy3($someModel)
    {
        // ...
        
        $relation = $this->memoize(function () use ($someModel) {
            return Foo::find($someModel->foo_relation_id);
        });
        
        // ...
    }
}

use LaracraftTech\Memoize\HasMemoization;

class MyClass
{
    use HasMemoization;
    
    public function __construct()
    {
        $this->disableMemoization();
    }
}