Skip to content

Commit

Permalink
add readme
Browse files Browse the repository at this point in the history
  • Loading branch information
kbond committed Mar 20, 2023
1 parent e32fec4 commit 6b4ef0a
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# zenstruck/memoize

Helper trait to efficiently cache expensive methods in memory.

## Installation

```bash
composer require zenstruck/memoize
```

## Usage

Add the memoize trait to an object you wish to cache operations on.

```php
use Zenstruck\Memoize;

class MyObject
{
use Memoize;

public function method1(): mixed
{
return $this->memoize(
__FUNCTION__, // memoize requires a "cache key" an easy choice is the function name
fn() => $this->someExpensiveOperation() // called only the first time method1() is called
);
}

public function method2(string $parameter): mixed
{
return $this->memoize(
__FUNCTION__.$parameter, // cache key includes the parameter
fn() => $this->someExpensiveOperation($parameter) // called once per unique parameter
)
}

public function refresh(): void
{
$this->clearMemoized(); // clear all cached values for this object instance
$this->clearMemoized('method1'); // clear just the cached value for "method1"
}
}
```

> **Note**: The cached values are stored in a `WeakMap` keyed by each object's instance. They are
> automatically cleared as the objects are garbage collected.

0 comments on commit 6b4ef0a

Please sign in to comment.