{"id":13593487,"url":"https://github.com/spatie/once","last_synced_at":"2025-05-12T22:45:22.325Z","repository":{"id":12874022,"uuid":"73020509","full_name":"spatie/once","owner":"spatie","description":"A magic memoization function","archived":false,"fork":false,"pushed_at":"2025-05-12T06:48:19.000Z","size":596,"stargazers_count":1364,"open_issues_count":0,"forks_count":58,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-05-12T22:45:05.116Z","etag":null,"topics":["cache","magic","performance","php"],"latest_commit_sha":null,"homepage":"https://spatie.be/opensource","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"custom":"https://spatie.be/open-source/support-us"}},"created_at":"2016-11-06T21:34:54.000Z","updated_at":"2025-05-12T06:48:15.000Z","dependencies_parsed_at":"2025-02-11T14:21:11.355Z","dependency_job_id":"961064b2-f0b2-496c-a8b7-6fdab6141d8b","html_url":"https://github.com/spatie/once","commit_stats":{"total_commits":129,"total_committers":32,"mean_commits":4.03125,"dds":0.4728682170542635,"last_synced_commit":"b9e7c4c9ce48a88723c3bd7ee66e30074d7dbf03"},"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fonce","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fonce/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fonce/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fonce/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/once/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253837387,"owners_count":21971981,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","magic","performance","php"],"created_at":"2024-08-01T16:01:20.780Z","updated_at":"2025-05-12T22:45:22.299Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://spatie.be/open-source/support-us"],"categories":["PHP"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\u003cimg src=\"/art/socialcard.png\" alt=\"Social Card of Once\"\u003e\u003c/p\u003e\n\n# A magic [memoization](https://en.wikipedia.org/wiki/Memoization) function\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/once.svg?style=flat-square)](https://packagist.org/packages/spatie/once)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n[![Build Status](https://img.shields.io/travis/spatie/once/master.svg?style=flat-square)](https://travis-ci.org/spatie/once)\n[![Quality Score](https://img.shields.io/scrutinizer/g/spatie/once.svg?style=flat-square)](https://scrutinizer-ci.com/g/spatie/once)\n[![StyleCI](https://styleci.io/repos/73020509/shield?branch=master)](https://styleci.io/repos/73020509)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/once.svg?style=flat-square)](https://packagist.org/packages/spatie/once)\n\nThis package contains a `once` function. You can pass a `callable` to it. Here's quick example:\n\n```php\n$myClass = new class() {\n    public function getNumber(): int\n    {\n        return once(function () {\n            return rand(1, 10000);\n        });\n    }\n};\n```\n\nNo matter how many times you run `$myClass-\u003egetNumber()` inside the same request  you'll always get the same number.\n\n## Are you a visual learner?\n\nUnder the hood, this package uses a PHP 8 Weakmap. [In this video](https://www.youtube.com/watch?v=-lFyHJqzfFU\u0026list=PLjzBMxW2XGTwEwWumYBaFHy1z4W32TcjU\u0026index=13), you'll see what a weakmap is, together with a nice demo of the package.\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/once.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/once)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe 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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Installation\n\nYou can install the package via composer:\n\n``` bash\ncomposer require spatie/once\n```\n\n## Usage\n\nThe `once` function accepts a `callable`.\n\n```php\n$myClass = new class() {\n    public function getNumber(): int\n    {\n        return once(function () {\n            return rand(1, 10000);\n        });\n    }\n};\n```\n\nNo matter how many times you run `$myClass-\u003egetNumber()` you'll always get the same number.\n\nThe `once` function will only run once per combination of argument values the containing method receives.\n\n```php\nclass MyClass\n{\n    /**\n     * It also works in static context!\n     */\n    public static function getNumberForLetter($letter)\n    {\n        return once(function () use ($letter) {\n            return $letter . rand(1, 10000000);\n        });\n    }\n}\n```\n\nSo calling `MyClass::getNumberForLetter('A')` will always return the same result, but calling `MyClass::getNumberForLetter('B')` will return something else.\n\n### Flushing the cache\n\nTo flush the entire cache you can call:\n\n```php\nSpatie\\Once\\Cache::getInstance()-\u003eflush();\n```\n\n### Disabling the cache\n\nIn your tests you probably don't want to cache values. To disable the cache you can call:\n\n```php\nSpatie\\Once\\Cache::getInstance()-\u003edisable();\n```\n\nYou can re-enable the cache with\n\n```php\nSpatie\\Once\\Cache::getInstance()-\u003eenable();\n```\n\n### Octane compatibility\n\n\u003e **Warning**\n\u003e \n\u003e This behaviour is in beta and needs to be tested by the community. You can find this topic [in discussion #79](https://github.com/spatie/once/discussions/79).\n\nIn order to have `once` working properly in an Octane environment, `Cache::getInstance()-\u003eflush()` must be called when `OperationTerminated` event is triggered. You can configure it in `config/octane.php` file:\n\n```php\n// config/octane.php\n\nOperationTerminated::class =\u003e [\n    FlushTemporaryContainerInstances::class,\n    // DisconnectFromDatabases::class,\n    // CollectGarbage::class,\n\n    FlushSpatieOnce::class, // we should create this class we have added here\n],\n```\n\nAnd create the `FlushSpatieOnce:class`:\n\n```php\n// app/Listeners/FlushSpatieOnce.php\n\nuse Spatie\\Once\\Cache;\n\nclass FlushSpatieOnce\n{\n    public function handle($event)\n    {\n        Cache::getInstance()-\u003eflush();\n    }\n}\n```\n\n## Under the hood\n\nThe `once` function will execute the given callable and save the result in the  `$values` property of `Spatie\\Once\\Cache`. This class [is a singleton](https://github.com/spatie/once/blob/9decd70a76664ff451fb10f65ac360290a6a50e6/src/Cache.php#L15-L27). When we detect that `once` has already run before, we're just going to return the value stored inside [the `$values` weakmap](https://github.com/spatie/once/blob/9decd70a76664ff451fb10f65ac360290a6a50e6/src/Cache.php#L11) instead of executing the callable again.\n\nThe first thing it does is calling [`debug_backtrace`](http://php.net/manual/en/function.debug-backtrace.php). 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.\n\n```php\n$trace = debug_backtrace(\n    DEBUG_BACKTRACE_PROVIDE_OBJECT, 2\n)[1];\n\n$backtrace = new Backtrace($trace);\n\n$object = $backtrace-\u003egetObject();\n```\n\nNext, 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.\n\n```php\n$hash = $backtrace-\u003egetHash();\n```\n\nFinally, 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).\n\n```php\npublic function has(object $object, string $backtraceHash): bool\n{\n    if (! isset($this-\u003evalues[$object])) {\n\n        return false;\n    }\n\n    return array_key_exists($backtraceHash, $this-\u003evalues[$object]);\n}\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Testing\n\n``` bash\ncomposer test\n```\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Credits\n\n- [Freek Van der Herten](https://github.com/freekmurze)\n- [All Contributors](../../contributors)\n\nAnd a special thanks to [Caneco](https://twitter.com/caneco) for the logo ✨\n\nCredit for the idea of the `once` function goes to [Taylor Otwell](https://twitter.com/taylorotwell/status/794622206567444481). The code for this package is based upon the code he was kind enough to share with us.\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fonce","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Fonce","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fonce/lists"}