h4kuna/memoize

Provide cache to memory for your class.

Installs: 70 894

Dependents: 4

Suggesters: 0

Security: 0

Stars: 4

Watchers: 3

Forks: 0

Open Issues: 0

Type:tool

v0.1.7 2024-08-23 05:52 UTC

This package is auto-updated.

Last update: 2024-12-23 06:28:01 UTC


README

Downloads this Month Latest stable

Is one trait whose provide cache to memory for classes. This is abstract standard use case how cache data for one request. Example is below.

Api is easy where is one method memoize where first parameter is unique key string or array and second parameter is callback. This trait clear class.

Install by composer

$ composer require h4kuna/memoize

Standard use case

<?php

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];
	}

}

Use Memoize

<?php

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);
		});
	}

}

Static use case

The similar class can be used for static class.

class Bar {
	use h4kuna\Memoize\MemoizeStatic

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

Use both traits

This case is unlikely, so the names are the same. You can resolve by alias.

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();
	}
}

Disable Memoize in tests

You can disable Memoize for tests in bootstrap.

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