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)15671MITPHPPHP ^8.1CI passing

Since Nov 5Pushed 1w 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 today

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

41

—

FairBetter than 87% of packages

Maintenance64

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 51.2% 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

1234d 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 (43 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (25 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (16 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

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[drush/drush

Drush is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt.

2.4k60.6M804](/packages/drush-drush)[snc/redis-bundle

A Redis bundle for Symfony

1.0k40.9M75](/packages/snc-redis-bundle)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[spatie/flare-client-php

Send PHP errors to Flare

177161.5M23](/packages/spatie-flare-client-php)

PHPackages © 2026

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