h4kuna / memoize
Provide cache to memory for your class.
Installs: 65 943
Dependents: 4
Suggesters: 0
Security: 0
Stars: 4
Watchers: 3
Forks: 0
Open Issues: 0
Type:tool
Requires
- php: >=8.0.0
- psr/simple-cache: ^3.0
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpstan/phpstan-strict-rules: ^1.4
- phpunit/phpunit: ^11.2
This package is auto-updated.
Last update: 2024-10-23 06:08:36 UTC
README
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();