All Projects → spatie → Once

spatie / Once

Licence: mit
A magic memoization function

Projects that are alternatives of or similar to Once

Laravel Blink
Cache that expires in the blink of an eye
Stars: ✭ 114 (-86.11%)
Mutual labels:  cache, performance
Scaffeine
Thin Scala wrapper for Caffeine (https://github.com/ben-manes/caffeine)
Stars: ✭ 195 (-76.25%)
Mutual labels:  cache, performance
Craft Blitz
Intelligent static page caching for creating lightning-fast sites with Craft CMS.
Stars: ✭ 118 (-85.63%)
Mutual labels:  cache, performance
Kirby3 Autoid
Automatic unique ID for Pages, Files and Structures including performant helpers to retrieve them. Bonus: Tiny-URL.
Stars: ✭ 58 (-92.94%)
Mutual labels:  cache, performance
Bigcache
Efficient cache for gigabytes of data written in Go.
Stars: ✭ 5,304 (+546.04%)
Mutual labels:  cache, performance
Fast React Render
[DEPRECATED] Use last versions of React and Node.js for better performance
Stars: ✭ 102 (-87.58%)
Mutual labels:  cache, performance
Fragment Cache
WordPress plugin for partial and async caching.
Stars: ✭ 135 (-83.56%)
Mutual labels:  cache, performance
Lazycache
An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
Stars: ✭ 901 (+9.74%)
Mutual labels:  cache, performance
Guzzle Cache Middleware
A HTTP Cache for Guzzle 6. It's a simple Middleware to be added in the HandlerStack.
Stars: ✭ 325 (-60.41%)
Mutual labels:  cache, performance
Ristretto
A high performance memory-bound Go cache
Stars: ✭ 3,584 (+336.54%)
Mutual labels:  cache, performance
Ansible Role Memcached
Ansible Role - Memcached
Stars: ✭ 54 (-93.42%)
Mutual labels:  cache, performance
Bloom
🌸 HTTP REST API caching middleware, to be used between load balancers and REST API workers.
Stars: ✭ 553 (-32.64%)
Mutual labels:  cache, performance
Pomodoro
A simple WordPress translation cache
Stars: ✭ 47 (-94.28%)
Mutual labels:  cache, performance
Quitnow Cache
A collection to store data for a given time
Stars: ✭ 109 (-86.72%)
Mutual labels:  cache, performance
Wordpress Rest Cache
WordPress Plugin to lazy cache HTTP requests in database and update via cron.
Stars: ✭ 8 (-99.03%)
Mutual labels:  cache, performance
Laravel Responsecache
Speed up a Laravel app by caching the entire response
Stars: ✭ 1,874 (+128.26%)
Mutual labels:  cache, performance
Laravel Partialcache
Blade directive to cache rendered partials in laravel
Stars: ✭ 205 (-75.03%)
Mutual labels:  cache, performance
React Esi
React ESI: Blazing-fast Server-Side Rendering for React and Next.js
Stars: ✭ 537 (-34.59%)
Mutual labels:  cache, performance
Django Cachalot
No effort, no worry, maximum performance.
Stars: ✭ 790 (-3.78%)
Mutual labels:  cache, performance
Domtastic
Small, fast, and modular DOM and event library for modern browsers.
Stars: ✭ 763 (-7.06%)
Mutual labels:  performance

Social Card of Once

A magic memoization function

Latest Version on Packagist Software License Build Status Quality Score StyleCI Total Downloads

This package contains a once function. You can pass a callable to it. Here's quick example:

$myClass = new class() {
    public function getNumber(): int
    {
        return once(function () {
            return rand(1, 10000);
        });
    }
};

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

Are you a visual learner?

Under the hood, this package uses a PHP 8 Weakmap. In this video, you'll see what a weakmap is, together with a nice demo of the package.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/once

Usage

The once function accepts a callable.

$myClass = new class() {
    public function getNumber(): int
    {
        return once(function () {
            return rand(1, 10000);
        });
    }
};

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

The once function will only run once per combination of argument values the containing method receives.

class MyClass
{
    /**
     * It also works in static context!
     */
    public static function getNumberForLetter($letter)
    {
        return once(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.

Flushing the cache

To flush the entire cache you can call:

Spatie\Once\Cache::getInstance()->flush();

Disabling the cache

In your test you probably don't want to cache values. To disable the cache you can call:

Spatie\Once\Cache::getInstance()->disable();

You can re-enable the cache with

Spatie\Once\Cache::getInstance()->enable();

Under the hood

The once function will execute the given callable and save the result in the $values property of Spatie\Once\Cache. This class is a singleton. When we detect that once has already run before, we're just going to return the value stored inside the $values weakmap instead of executing the callable again.

The first thing it does is calling debug_backtrace. We'll use the output to determine in which function and class once is called and to get access to the object that function is running in. Yeah, we're already in voodoo-land. The output of the debug_backtrace is passed to a new instance of Backtrace. That class is just a simple wrapper, so we can work more easily with the backtrace.

$trace = debug_backtrace(
    DEBUG_BACKTRACE_PROVIDE_OBJECT, 2
)[1];

$backtrace = new Backtrace($trace);

$object = $backtrace->getObject();

Next, we calculate a hash of the backtrace. This hash will be unique per function once was called in and the values of the arguments that function receives.

$hash = $backtrace->getHash();

Finally, we will check if there's already a value stored for the given hash. If not, then execute the given $callback and store the result in the weakmap of Spatie\Once\Cache. In the other case, we just return the value from that cache (the $callback isn't executed).

public function has(object $object, string $backtraceHash): bool
{
    if (! isset($this->values[$object])) {

        return false;
    }

    return array_key_exists($backtraceHash, $this->values[$object]);
}

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

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

Credits

And a special thanks to Caneco for the logo ✨

Credit for the idea of the once function goes to Taylor Otwell. The code for this package is based upon the code he was kind enough to share with us.

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].