All Projects → yiisoft → cache

yiisoft / cache

Licence: BSD-3-Clause License
PSR-16 compatible cache library

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to cache

WP-Stash
Bridge between WordPress and StashPHP, providing a PSR6-compliant caching system for WordPress
Stars: ✭ 31 (+3.33%)
Mutual labels:  cache
auth
www.yiiframework.com/
Stars: ✭ 28 (-6.67%)
Mutual labels:  yii3
auth-jwt
www.yiiframework.com/
Stars: ✭ 28 (-6.67%)
Mutual labels:  yii3
netlify-plugin-cache
⚡ Generic plugin for caching any files and/or folders between Netlify builds
Stars: ✭ 19 (-36.67%)
Mutual labels:  cache
tiny-cache
Cache WordPress post content, template part, translations and nav menu output in persistent object cache
Stars: ✭ 26 (-13.33%)
Mutual labels:  cache
KJNetworkPlugin
🎡A lightweight but powerful Network library. Network Plugin, Support batch and chain operation. 插件版网络架构
Stars: ✭ 43 (+43.33%)
Mutual labels:  cache
package-template
A template for a new package within yiisoft
Stars: ✭ 26 (-13.33%)
Mutual labels:  yii3
infinitree
Scalable and encrypted embedded database with 3-tier caching
Stars: ✭ 80 (+166.67%)
Mutual labels:  cache
bazel-cache
Minimal cloud oriented Bazel gRPC cache
Stars: ✭ 33 (+10%)
Mutual labels:  cache
fastapi-cache
fastapi-cache is a tool to cache fastapi response and function result, with backends support redis and memcached.
Stars: ✭ 375 (+1150%)
Mutual labels:  cache
public
util toolkit for go.golang 通用函数包
Stars: ✭ 135 (+350%)
Mutual labels:  cache
memoize
Caching library for asynchronous Python applications.
Stars: ✭ 53 (+76.67%)
Mutual labels:  cache
varnish-cache-reaper
Simple python/twisted HTTP daemon forwarding PURGE and BAN requests to multiple varnish (or other proxy) instances
Stars: ✭ 12 (-60%)
Mutual labels:  cache
go-memoize
An easy, no-frills memoizer for Go. Cache your expensive function calls.
Stars: ✭ 63 (+110%)
Mutual labels:  cache
ultrafetch
Node-based fetch backed with an RFC-7234 compliant filesystem cache.
Stars: ✭ 30 (+0%)
Mutual labels:  cache
nginx-cache
Node.js module to find files in an Nginx cache based on partial URL keys
Stars: ✭ 24 (-20%)
Mutual labels:  cache
tacky
Primitive Object Memoization for Ruby
Stars: ✭ 14 (-53.33%)
Mutual labels:  cache
CacheLib
Pluggable in-process caching engine to build and scale high performance services
Stars: ✭ 637 (+2023.33%)
Mutual labels:  cache
cache-command
Manages object and transient caches.
Stars: ✭ 12 (-60%)
Mutual labels:  cache
moment-cache
⏱ Simple utility to cache moment.js results and speed up moment calls.
Stars: ✭ 29 (-3.33%)
Mutual labels:  cache

Yii Caching Library


Latest Stable Version Total Downloads Build status Scrutinizer Code Quality Code Coverage Mutation testing badge static analysis type-coverage

This library is a wrapper around PSR-16 compatible caching libraries providing own features. It is used in Yii Framework but is usable separately.

Features

  • Built on top of PSR-16, it can use any PSR-16 cache as a handler.
  • Ability to set default TTL and key prefix per cache instance.
  • Provides a built-in behavior to cache stampede prevention.
  • Adds cache invalidation dependencies on top of PSR-16.

Requirements

  • PHP 7.4 or higher.
  • JSON PHP extension.
  • Mbstring PHP extension.

Installation

The package could be installed with composer:

composer require yiisoft/cache --prefer-dist

Configuration

There are two ways to get cache instance. If you need PSR-16 instance, you can simply create it:

$arrayCache = new \Yiisoft\Cache\ArrayCache();

In order to set a global key prefix:

$arrayCacheWithPrefix = new \Yiisoft\Cache\PrefixedCache(new \Yiisoft\Cache\ArrayCache(), 'myapp_');

If you need a simpler yet more powerful way to cache values based on recomputation callbacks use getOrSet() and remove(), additional features such as invalidation dependencies and "Probably early expiration" stampede prevention, you should wrap PSR-16 cache instance with \Yiisoft\Cache\Cache:

$cache = new \Yiisoft\Cache\Cache($arrayCache);

Set a default TTL:

$cache = new \Yiisoft\Cache\Cache($arrayCache, 60 * 60); // 1 hour

General usage

Typical PSR-16 cache usage is the following:

$cache = new \Yiisoft\Cache\ArrayCache();
$parameters = ['user_id' => 42];
$key = 'demo';

// Try retrieving $data from cache.
$data = $cache->get($key);
if ($data === null) {
    // $data is not found in cache, calculate it from scratch.
    $data = calculateData($parameters);
    
    // Store $data in cache for an hour so that it can be retrieved next time.
    $cache->set($key, $data, 3600);
}

// $data is available here.

In order to delete value you can use:

$cache->delete($key);
// Or all cache
$cache->clear();

To work with values in a more efficient manner, batch operations should be used:

  • getMultiple()
  • setMultiple()
  • deleteMultiple()

When using extended cache i.e. PSR-16 cache wrapped with \Yiisoft\Cache\Cache, you can use alternative syntax that is less repetitive:

$cache = new \Yiisoft\Cache\Cache(new \Yiisoft\Cache\ArrayCache());
$key = ['top-products', $count = 10];

$data = $cache->getOrSet($key, function (\Psr\SimpleCache\CacheInterface $cache) use ($count) {
    return getTopProductsFromDatabase($count);
}, 3600);

Normalization of the key occurs using the Yiisoft\Cache\CacheKeyNormalizer.

In order to delete value you can use:

$cache->remove($key);

You can use PSR-16 methods the following way, but remember that getting and setting the cache separately violates the "Probably early expiration" algorithm.

$value = $cache->psr()->get('myKey');

Invalidation dependencies

When using \Yiisoft\Cache\Cache, additionally to TTL for getOrSet() method you can specify a dependency that may trigger cache invalidation. Below is an example using tag dependency:

/**
 * @var callable $callable
 * @var \Yiisoft\Cache\CacheInterface $cache
 */

use Yiisoft\Cache\Dependency\TagDependency;

// Set multiple cache values marking both with a tag.
$cache->getOrSet('item_42_price', $callable, null, new TagDependency('item_42'));
$cache->getOrSet('item_42_total', $callable, 3600, new TagDependency('item_42'));

// Trigger invalidation by tag.
TagDependency::invalidate($cache, 'item_42');

Other dependencies:

  • Yiisoft\Cache\Dependency\CallbackDependency - invalidates the cache when callback result changes.
  • Yiisoft\Cache\Dependency\FileDependency - invalidates the cache based on file modification time.
  • Yiisoft\Cache\Dependency\ValueDependency - invalidates the cache when specified value changes.

You may combine multiple dependencies using Yiisoft\Cache\Dependency\AnyDependency or Yiisoft\Cache\Dependency\AllDependencies.

In order to implement your own dependency extend from Yiisoft\Cache\Dependency\Dependency.

Cache stampede prevention

A cache stampede is a type of cascading failure that can occur when massively parallel computing systems with caching mechanisms come under very high load. This behaviour is sometimes also called dog-piling. The \Yiisoft\Cache\Cache uses a built-in "Probably early expiration" algorithm that prevents cache stampede. This algorithm randomly fakes a cache miss for one user while others are still served the cached value. You can control its behavior with the fifth optional parameter of getOrSet(), which is a float value called $beta. By default, beta is 1.0, which is sufficient in most cases. The higher the value the earlier cache will be re-created.

/**
 * @var mixed $key
 * @var callable $callable
 * @var \DateInterval $ttl
 * @var \Yiisoft\Cache\CacheInterface $cache
 * @var \Yiisoft\Cache\Dependency\Dependency $dependency
 */

$beta = 2.0;
$cache->getOrSet($key, $callable, $ttl, $dependency, $beta);

Cache handlers

Below the handler refers to the implementations of PSR-16.

This package contains two handlers:

  • Yiisoft\Cache\ArrayCache - provides caching for the current request only by storing the values in an array.
  • Yiisoft\Cache\NullCache - does not cache anything reporting success for all methods calls.

Extra cache handlers are implemented as separate packages:

Testing

Unit testing

The package is tested with PHPUnit. To run tests:

./vendor/bin/phpunit

Mutation testing

The package tests are checked with Infection mutation framework with Infection Static Analysis Plugin. To run it:

./vendor/bin/roave-infection-static-analysis-plugin

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

./vendor/bin/psalm

License

The Yii Caching Library is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

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].