modethirteen/fluent-cache

PSR-16 兼容缓存组件的流畅缓存构建器 API

1.1.0 2021-01-01 01:32 UTC

This package is auto-updated.

Last update: 2024-09-12 09:49:24 UTC


README

PSR-16 兼容缓存组件的流畅缓存构建器 API

github.com codecov.io Latest Stable Version Latest Unstable Version

需求

  • PHP 7.4 (主要, 2.x)

安装

使用 Composer。有两种方式将 FluentCache 添加到您的项目中。

从 composer CLI

./composer.phar require modethirteen/fluent-cache

或向项目的 composer.json 中添加 modethirteen/fluent-cache

{
    "require": {
        "modethirteen/fluent-cache": "dev-main"
    }
}

dev-main 是主要开发分支。如果您在生产环境中使用 FluentCache,建议您使用稳定版本。

假设您已设置 Composer 的自动加载,FluentCache 可以在 modethirteen\FluentCache\ 命名空间中找到。

用法

FluentCache 提供的主要类型是 CacheBuilderCacheBuilder 是一个不可变对象,它接受对缓存的引用和匿名函数来生成缓存键、构建缓存对象、验证结果和钩子事件调度器。

CacheBuilder 负责并混淆了编排处理缓存数据最常见场景所需的步骤

  • 检查缓存中的对象
    • 如果未命中,则构建对象,将其设置在缓存中,并返回对象
    • 如果命中,则返回对象

管理这些步骤,选择要分析的内容,何时验证,或其他与缓存相关的决策不是调用代码的责任:调用者只想 获取 对象,它不应该关心对象来自缓存,数据是否过时,或者对象是否是第一次构建。CacheBuilder 分离了这个关注点并封装它,同时提供自定义逻辑钩子以实现合理的灵活性。

class Memcache implements \Psr\SimpleCache\CacheInterface {}

class Dispatcher implements \Psr\EventDispatcher\EventDispatcherInterface {}

$result = (new CacheBuilder())
    ->withCache(new Memcache(), function() : ?string {

        // generate a cache key - if null is returned, then the cache will be ignored
        return 'foo';
    })
    ->withCacheLifespanBuilder(function($result) : int {

        // what is the ttl for objects set in the cache?
        return 1500;
    })
    ->withCacheValidator(function($result) : bool {

        // assert that cached object is valid when fetched
        if(!($result instanceof Bar)) {
            return false;
        }
        return $result->someProperty === 'some value';
    })
    ->withBuilder(function() : object {

        // build a cacheable object if cache miss
        return new Bar();
    })
     ->withBuildValidator(function($result) : object {

        // assert that post-cache miss built object is valid
        return $result instanceof Bar;
    })

    // send cache and build stage events to trigger downstream actions such as profiling
    ->withEventDispatcher(new Dispatcher())

    // ...or set a lazy dispatcher to initialize when we attempt to fetch an object
    ->withLazyEventDispatcher(function(CacheBuilder $this) : EventDispatcherInterface {
        return new Dispatcher();
    })
 
    // set a custom identifier to track this cache session in downstream event processors
    // ...session ids are automatically generated if not provided
    // ...session ids are re-generated everytime the immutable cache builder is cloned 
    ->withSessionId('123')
 
    // fetch object from cache or build it and set it in the cache - the caller doesn't care!
    ->get();