PHP code example of h4kuna / memoize

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

    

h4kuna / memoize example snippets




class Foo
{

	private $dataFromDatabase;

	private $users = [];


	public function loadDataFromDatabase()
	{
		if ($this->dataFromDatabase === null) {
			$this->dataFromDatabase = $this->repository->fetchAnyData();
		}
		return $this->dataFromDatabase;
	}


	public function loadDataFromDatabaseByUser($userId)
	{
		if (isset($this->users[$userId]) === false) {
			$this->users[$userId] = $this->repository->fetchUser($userId);
		}
		return $this->users[$userId];
	}

}



class Foo
{
	use h4kuna\Memoize\Memoize;

	public function loadDataFromDatabase()
	{
		return $this->memoize(__METHOD__, function() {
			return $this->repository->fetchAnyData();
		});
	}


	public function loadDataFromDatabaseByUser($userId)
	{
		return $this->memoize([__METHOD__, $userId], function() use ($userId) {
			return $this->repository->fetchUser($userId);
		});
	}

}


class Bar {
	use h4kuna\Memoize\MemoizeStatic

	public static function loadDataFromDatabaseByUser($userId)
	{
		return static::memoize([__METHOD__, $userId], function() use ($userId) {
			return User::fetchUser($userId);
		});
	}
}

class Baz {
	use Memoize\Memoize, Memoize\MemoizeStatic {
		Memoize\Memoize::memoize insteadof Memoize\MemoizeStatic;
		Memoize\MemoizeStatic::memoize as memoizeStatic;
	}
	
	public function foo(): 
	{
		return $this->memoize();
	}
	
	public static function bar(): 
	{
		return static::memoizeStatic();
	}
}

use h4kuna\Memoize\Helper;
Helper::bypassMemoize();