PHPackages                             laracraft-tech/memoize - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. laracraft-tech/memoize

ActiveLibrary[Caching](/categories/caching)

laracraft-tech/memoize
======================

Simple PHP trait to memoize function calls.

v1.0.3(3y ago)15661[2 PRs](https://github.com/laracraft-tech/memoize/pulls)MITPHPPHP ^8.1CI passing

Since Nov 5Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/laracraft-tech/memoize)[ Packagist](https://packagist.org/packages/laracraft-tech/memoize)[ RSS](/packages/laracraft-tech-memoize/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (4)Versions (8)Used By (0)

Memoize
=======

[](#memoize)

[![Latest Version on Packagist](https://camo.githubusercontent.com/915dba9764280aebec5498d830803a2d2b219d1e5bccf461f683cb1bbb8104cf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c61726163726166742d746563682f6d656d6f697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/laracraft-tech/memoize)[![Tests](https://github.com/laracraft-tech/memoize/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/laracraft-tech/memoize/actions/workflows/run-tests.yml)[![Check & fix styling](https://github.com/laracraft-tech/memoize/actions/workflows/fix-php-code-style-issues.yml/badge.svg?branch=main)](https://github.com/laracraft-tech/memoize/actions/workflows/fix-php-code-style-issues.yml)[![License](https://camo.githubusercontent.com/bba7105de0a33f0ecb5843f50c77fc558244b3eee7de30e997e95c2b31d65018/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c61726163726166742d746563682f6d656d6f697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/laracraft-tech/memoize)

Introduction
------------

[](#introduction)

This package provides you with a simple PHP trait, which adds high-performance [memoization](https://en.wikipedia.org/wiki/Memoization) to your classes!

Installation
------------

[](#installation)

```
$ composer require laracraft-tech/memoize
```

Usage
-----

[](#usage)

The `memoize` method accepts a `callable`.

```
use LaracraftTech\Memoize\HasMemoization;

$myClass = new class()
{
    use HasMemoization;

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

No matter how many times you run `$myClass->getNumber()` you'll always get the same number.

The `memoize` method will only run **once per combination** of `use` variables the ***closure*** receives.

```
$myClass = new class()
{
    use HasMemoization;

    public function getNumberForLetter($letter)
    {
        return $this->memoize(function () use ($letter) {
            return $letter . rand(1, 10000000);
        });
    }
}
```

So calling `$myClass->getNumberForLetter('A')` will always return the same result, but calling `$myClass->getNumberForLetter('B')` will return something else.

Some memoization packages uses the arguments of the ***containing method*** for the **once per combination** idea. We think this feels a bit unintuitive and in certain circumstances will affect performance. So we use the `use` variables of the closure as the **once per combination** key. As a fallback, if you like/need to, we also let you fully self define your **once per combination** key in a second optional parameter of the closure.

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

        // ...
    }
}
```

So when calling `$myClass->processSomethingHeavy1(SomeModel::find(1))` the variable `$relation` will always have the same value like in `$myClass->processSomethingHeavy1(SomeModel::find(2))` as long as they have the same `foo_relation_id`. In some other memoization packges you would lose performance here, cause the ***containing method*** parameter ($someModel) has changed... Note that `processSomethingHeavy3` would also lose performance, even though the `foo_relation_id` would be the same, cause here also the changed **$someModel** would be used as the combination key and that model would have at least a different id.

Enable/Disable
--------------

[](#enabledisable)

You can globally enable or disable the memoize cache by setting `MEMOIZATION_GLOBALLY_DISABLED` to `true` in your `.env` file.

If you only want to disable to memoize cache for a specifiy class, do something like this:

```
use LaracraftTech\Memoize\HasMemoization;

class MyClass
{
    use HasMemoization;

    public function __construct()
    {
        $this->disableMemoization();
    }
}
```

Change log
----------

[](#change-log)

Please see the [changelog](changelog.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [contributing.md](contributing.md) for details and a todolist.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Zacharias Creutznacher](https://github.com/laracraft-tech)
- [All Contributors](../../contributors)

License
-------

[](#license)

MIT. Please see the [license file](license.md) for more information.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance60

Regular maintenance activity

Popularity17

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 52.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~33 days

Total

4

Last Release

1184d ago

PHP version history (2 changes)v1.0.0PHP ^7.3|^8.0

v1.0.2PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/cf347b32c0d1fceabbcbce7626ad662faa34738396fd9f774231d55370823713?d=identicon)[Sairahcaz](/maintainers/Sairahcaz)

---

Top Contributors

[![Sairahcaz](https://avatars.githubusercontent.com/u/7384870?v=4)](https://github.com/Sairahcaz "Sairahcaz (41 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (22 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (15 commits)")

---

Tags

cachememoizationperformancephp

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/laracraft-tech-memoize/health.svg)

```
[![Health](https://phpackages.com/badges/laracraft-tech-memoize/health.svg)](https://phpackages.com/packages/laracraft-tech-memoize)
```

###  Alternatives

[predis/predis

A flexible and feature-complete Redis/Valkey client for PHP.

7.8k305.7M2.4k](/packages/predis-predis)[snc/redis-bundle

A Redis bundle for Symfony

1.0k39.4M67](/packages/snc-redis-bundle)[react/cache

Async, Promise-based cache interface for ReactPHP

444112.4M40](/packages/react-cache)[wp-media/wp-rocket

Performance optimization plugin for WordPress

7431.3M3](/packages/wp-media-wp-rocket)[illuminate/cache

The Illuminate Cache package.

12835.6M1.4k](/packages/illuminate-cache)[colinmollenhour/php-redis-session-abstract

A Redis-based session handler with optimistic locking

6325.6M14](/packages/colinmollenhour-php-redis-session-abstract)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
