Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Async, Promise-based cache interface for ReactPHP.

License

NotificationsYou must be signed in to change notification settings

reactphp/cache

Repository files navigation

CI statusinstalls on Packagist

Async,Promise-based cache interfaceforReactPHP.

Development version: This branch contains the code for the upcoming v3release. For the code of the current stable v1 release, check out the1.x branch.

The upcoming v3 release will be the way forward for this package. However,we will still actively support v1 for those not yet on the latest version.See alsoinstallation instructions for more details.

The cache component provides aPromise-basedCacheInterface and an in-memoryArrayCacheimplementation of that.This allows consumers to type hint against the interface and third parties toprovide alternate implementations.This project is heavily inspired byPSR-16: Common Interface for Caching Libraries,but uses an interface more suited for async, non-blocking applications.

Table of Contents

Usage

CacheInterface

TheCacheInterface describes the main interface of this component.This allows consumers to type hint against the interface and third parties toprovide alternate implementations.

get()

Theget(string $key, mixed $default = null): PromiseInterface<mixed> method can be used toretrieve an item from the cache.

This method will resolve with the cached value on success or with thegiven$default value when no item can be found or when an error occurs.Similarly, an expired cache item (once the time-to-live is expired) isconsidered a cache miss.

$cache    ->get('foo')    ->then('var_dump');

This example fetches the value of the keyfoo and passes it to thevar_dump function. You can use any of the composition provided bypromises.

set()

Theset(string $key, mixed $value, ?float $ttl = null): PromiseInterface<bool> method can be used tostore an item in the cache.

This method will resolve withtrue on success orfalse when an erroroccurs. If the cache implementation has to go over the network to storeit, it may take a while.

The optional$ttl parameter sets the maximum time-to-live in secondsfor this cache item. If this parameter is omitted (ornull), the itemwill stay in the cache for as long as the underlying implementationsupports. Trying to access an expired cache item results in a cache miss,see alsoget().

$cache->set('foo','bar',60);

This example eventually sets the value of the keyfoo tobar. If italready exists, it is overridden.

This interface does not enforce any particular TTL resolution, so specialcare may have to be taken if you rely on very high precision withmillisecond accuracy or below. Cache implementations SHOULD work on abest effort basis and SHOULD provide at least second accuracy unlessotherwise noted. Many existing cache implementations are known to providemicrosecond or millisecond accuracy, but it's generally not recommendedto rely on this high precision.

This interface suggests that cache implementations SHOULD use a monotonictime source if available. Given that a monotonic time source is onlyavailable as of PHP 7.3 by default, cache implementations MAY fall backto using wall-clock time.While this does not affect many common use cases, this is an importantdistinction for programs that rely on a high time precision or on systemsthat are subject to discontinuous time adjustments (time jumps).This means that if you store a cache item with a TTL of 30s and thenadjust your system time forward by 20s, the cache item SHOULD stillexpire in 30s.

delete()

Thedelete(string $key): PromiseInterface<bool> method can be used todelete an item from the cache.

This method will resolve withtrue on success orfalse when an erroroccurs. When no item for$key is found in the cache, it also resolvestotrue. If the cache implementation has to go over the network todelete it, it may take a while.

$cache->delete('foo');

This example eventually deletes the keyfoo from the cache. As withset(), this may not happen instantly and a promise is returned toprovide guarantees whether or not the item has been removed from cache.

getMultiple()

ThegetMultiple(iterable<string> $keys, mixed $default = null): PromiseInterface<iterable<string,mixed>> method can be used toretrieve multiple cache items by their unique keys.

This method will resolve with an array of cached values on success or with thegiven$default value when an item can not be found or when an error occurs.Similarly, an expired cache item (once the time-to-live is expired) isconsidered a cache miss.

$cache->getMultiple(['name','age'])->then(function (iterable$values):void {$array =is_array($values) ?$values :iterator_to_array($values);$name =$array['name'] ??'User';$age =$array['age'] ??'n/a';echo$name .' is' .$age .PHP_EOL;});

This example fetches the cache items for thename andage keys andprints some example output. You can use any of the composition providedbypromises.

setMultiple()

ThesetMultiple(iterable<string,mixed> $values, ?float $ttl = null): PromiseInterface<bool> method can be used topersist a set of key => value pairs in the cache, with an optional TTL.

This method will resolve withtrue on success orfalse when an erroroccurs. If the cache implementation has to go over the network to storeit, it may take a while.

The optional$ttl parameter sets the maximum time-to-live in secondsfor these cache items. If this parameter is omitted (ornull), these itemswill stay in the cache for as long as the underlying implementationsupports. Trying to access an expired cache items results in a cache miss,see alsogetMultiple().

$cache->setMultiple(['foo' =>1,'bar' =>2],60);

This example eventually sets the list of values - the keyfoo to1 valueand the keybar to2. If some of the keys already exist, they are overridden.

deleteMultiple()

ThesetMultiple(iterable<string> $keys): PromiseInterface<bool> method can be used todelete multiple cache items in a single operation.

This method will resolve withtrue on success orfalse when an erroroccurs. When no items for$keys are found in the cache, it also resolvestotrue. If the cache implementation has to go over the network todelete it, it may take a while.

$cache->deleteMultiple(['foo','bar,'baz']);

This example eventually deletes keysfoo,bar andbaz from the cache.As withsetMultiple(), this may not happen instantly and a promise is returned toprovide guarantees whether or not the item has been removed from cache.

clear()

Theclear(): PromiseInterface<bool> method can be used towipe clean the entire cache.

This method will resolve withtrue on success orfalse when an erroroccurs. If the cache implementation has to go over the network todelete it, it may take a while.

$cache->clear();

This example eventually deletes all keys from the cache. As withdeleteMultiple(),this may not happen instantly and a promise is returned to provide guaranteeswhether or not all the items have been removed from cache.

has()

Thehas(string $key): PromiseInterface<bool> method can be used todetermine whether an item is present in the cache.

This method will resolve withtrue on success orfalse when no item can be foundor when an error occurs. Similarly, an expired cache item (once the time-to-liveis expired) is considered a cache miss.

$cache    ->has('foo')    ->then('var_dump');

This example checks if the value of the keyfoo is set in the cache and passesthe result to thevar_dump function. You can use any of the composition provided bypromises.

NOTE: It is recommended that has() is only to be used for cache warming type purposesand not to be used within your live applications operations for get/set, as this methodis subject to a race condition where your has() will return true and immediately after,another script can remove it making the state of your app out of date.

ArrayCache

TheArrayCache provides an in-memory implementation of theCacheInterface.

$cache =newArrayCache();$cache->set('foo','bar');

Its constructor accepts an optional?int $limit parameter to limit themaximum number of entries to store in the LRU cache. If you add moreentries to this instance, it will automatically take care of removingthe one that was least recently used (LRU).

For example, this snippet will overwrite the first value and only storethe last two entries:

$cache =newArrayCache(2);$cache->set('foo','1');$cache->set('bar','2');$cache->set('baz','3');

This cache implementation is known to rely on wall-clock time to schedulefuture cache expiration times when using any version before PHP 7.3,because a monotonic time source is only available as of PHP 7.3 (hrtime()).While this does not affect many common use cases, this is an importantdistinction for programs that rely on a high time precision or on systemsthat are subject to discontinuous time adjustments (time jumps).This means that if you store a cache item with a TTL of 30s on PHP < 7.3and then adjust your system time forward by 20s, the cache item mayexpire in 10s. See alsoset() for more details.

Common usage

Fallback get

A common use case of caches is to attempt fetching a cached value and as afallback retrieve it from the original data source if not found. Here is anexample of that:

$cache    ->get('foo')    ->then(function ($result) {if ($result ===null) {returngetFooFromDb();        }return$result;    })    ->then('var_dump');

First an attempt is made to retrieve the value offoo. A callback function isregistered that will callgetFooFromDb when the resulting value is null.getFooFromDb is a function (can be any PHP callable) that will be called if thekey does not exist in the cache.

getFooFromDb can handle the missing key by returning a promise for theactual value from the database (or any other data source). As a result, thischain will correctly fall back, and provide the value in both cases.

Fallback get and set

To expand on the fallback get example, often you want to set the value on thecache after fetching it from the data source.

$cache    ->get('foo')    ->then(function ($result) {if ($result ===null) {return$this->getAndCacheFooFromDb();        }return$result;    })    ->then('var_dump');publicfunctiongetAndCacheFooFromDb(){return$this->db        ->get('foo')        ->then([$this,'cacheFooFromDb']);}publicfunctioncacheFooFromDb($foo){$this->cache->set('foo',$foo);return$foo;}

By using chaining you can easily conditionally cache the value if it isfetched from the database.

Install

The recommended way to install this library isthrough Composer.New to Composer?

Once released, this project will followSemVer.At the moment, this will install the latest development version:

composer require react/cache:^3@dev

See also theCHANGELOG for details about version upgrades.

This project aims to run on any platform and thus does not require any PHPextensions and supports running on PHP 7.1 through current PHP 8+.It'shighly recommended to use the latest supported PHP version for this project.

Tests

To run the test suite, you first need to clone this repo and then install alldependenciesthrough Composer:

composer install

To run the test suite, go to the project root and run:

vendor/bin/phpunit

On top of this, we use PHPStan on max level to ensure type safety across the project:

vendor/bin/phpstan

License

MIT, seeLICENSE file.

About

Async, Promise-based cache interface for ReactPHP.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

  •  
  •  
  •  

Contributors12

Languages


[8]ページ先頭

©2009-2025 Movatter.jp